Angular doesn't require ng-click
I am creating an export function for my app in angular. I need to click buttons that will call the export function in the scope. I tried to use ng-click="myFunction()"
but the export is not being called ...
Here is my jade pattern
ul.dropdown-menu(role='menu' aria-labelledby='dLabel')
li
a(export-content-as, export-type='markdown',
export-content='properties.quill.getHTML',
href='', ng-click="exportAs()") Export as markdown
li
a(export-content-as, export-type='raw',
export-content='properties.quill.getText',
href='', ng-click="exportAs()") Export as text
li
a(export-content-as, export-type='pdf',
export-content='properties.quill.getContents',
href='', ng-click="exportAs()") Export as PDF
and my js file:
angular.module('foo', [])
…
.directive('exportContentAs', ['properties', '$window', 'exportRawText', 'exportMarkdown', 'exportPdf',
function(properties, $window, exportRawText, exportMarkdown, exportPdf) {
function link(scope, element) {
scope.exportAs = function() {
switch (scope.type) {
case 'markdown':
exportMarkdown(scope.exportContent());
break;
case 'raw':
exportRawText(scope.exportContent());
break;
case 'pdf':
exportPdf(scope.exportContent());
break;
default:
break;
}
};
}
return {
scope: {
exportType: '@',
exportContent: '&'
},
link: link,
restrict: 'A'
};
}
]);
I know the module is loaded (I am calling a different directive elsewhere in my code). I also know that when any of the links are clicked, the scope.exportAs function is not called.
I can also bind a click to a call exportAs
using element.on('click', exportAs)
, but I would like to understand why I need this (not only ng-click="exportAs"
).
source to share
you can just go with the normal way of binding the click event for the directive. If you insist on using ng-click with anchor tag with attribute directive, you can try something like this:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.type = "raw";
$scope.exportAs = function(exportType) {
switch (exportType) {
case 'markdown':
alert('markdown');
break;
case 'raw':
alert('raw');
break;
case 'pdf':
alert('pdf');
break;
default:
alert(exportType);
break;
}
};
});
app.directive('exportContentAs',
function() {
return {
scope: {
exportType: '=',
eventHandler: '&ngClick'
},
restrict: 'A'
};
}
);
Using:
<body ng-controller="MainCtrl">
<a export-content-as export-type='type'
href ng-click="exportAs(type)"> TEST</a>
</body>
source to share
This is because Angular is exportAs
not looking for the function in the selection scope of your directive, but in the controller scope (parent scope). There is another approach:
- remove marquee from your directive
- pass file type and name directly to
exportAs
Here is a plucker demonstrating this: http://plnkr.co/edit/AKIRZ2DZIJOHLsC0b95O
Hope this helps you understand.
source to share