1

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.

Aetherus
  • 8,720
  • 1
  • 22
  • 36

2 Answers2

2

Rather than using link inside compile use the link function directly as shown below

link: function(scope, element, attrs) {
element.onClick(function(){
      $log.debug('myDirective is clicked');
});
}

You can directly add the click handler to the element, you need not bind ng-click directive inside your directive.

MeanMan
  • 1,040
  • 10
  • 25
  • that worked for me! My directive is using controller instead of linker, so I put the code there, but it worked the same. Note that this won't add any attribute to the element so you won't necessarily see the click event in the DOM inspector – chiliNUT Feb 13 '17 at 18:02
  • On AngularJS version 1.4.6 onClick didn't work (got a "is not a function" error). I had to use `element.on('click', function () {` – Marco Lackovic Jul 19 '18 at 08:23
1

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); 
                });
           }
      };
});
Sagar Naliyapara
  • 3,971
  • 5
  • 41
  • 61
  • So there's no pure angular way to solve this problem, and I have to turn to jQuery or jqlite, right? – Aetherus Jun 14 '16 at 03:49
  • @Aetherus no it's not like that you can do it with angular as i have written code of it you can see it here http://jsfiddle.net/jigardafda/w9w65tk7/1/ – Sagar Naliyapara Jun 14 '16 at 03:53