Aetherus Aetherus - 5 months ago 36
AngularJS Question

Can't add ngClick to attribute directive

I want to dynamically add

ngClick
to an attribute directive.

javascript

angular.module('app')
.directive('myDirective', ['$log', function ($log) {
return {
restrict: 'A', // PAY ATTENTION TO THIS LINE
compile: function (tElement) {
tElement.attr('ng-click', 'onClick()');
return function postLink(scope) {
scope.onClick = function () {
$log.debug('myDirective is clicked');
}
}
}
}
}]);


markup

<button my-directive>Click Me</button>


From the element inspector of Chrome, I can see that the
ng-click
attribute is added to the button.

I expect to see the text "myDirective is clicked." in the console when the button is clicked, but actually there's nothing printed. No error is raised. Anyone can help? Thanks in advance.

Answer

Hello please try this one,

HTML:

<div ng-app="angularApp">
    <div ng-controller="dirCtrl1">
        <button ng-click="clickFun('clicked')">Button</button>
        <button my-directive="directive">With directive</button>
    </div>
 </div>

JS:

.controller('dirCtrl1', function ($scope) {
    $scope.clickFun = function (msg) {
        console.log(msg);
    };
})
.directive('myDirective', function(){
      return{
           restrict: 'A',
           link: function(scope, ele, attr){
                var eventName = attr.evetName || 'click';
                var mas = attr.myDirective || 'just console';
                ele.on(eventName, function(){
                   console.log(mas); 
                });
           }
      };
});