Lukas Chen
Lukas Chen

Reputation: 383

AngularJS What is the benefit of binding click in angular directive over ng-click?

I have seen some people binding click in there directive's link function over than ng-click.

I have researched for a long time and haven't found the answer. Can anyone give me a reason?

I have been using ng-click because it is much easier than creating a new directive,and I can get an overview in a glance.

Example

How I write a directive

HTML

<some-directive>
  <button ng-click="someFunction()">Lorem Ipsum</button>
</some-directive>

Javascript

angular.module('myapp',[])
.directive('someDirective',function(){
  return {
    restrict:'E',
    scope:{},
    link: function (scope,element,attrs) {

      //Code goes here

      scope.someFunction = function() {
        //callback
      }

      //More code goes here

    }
  }
})

How most people write a directive

html

<some-directive>
  <button click-trigger>Lorem Ipsum</button>
</some-directive>

Javascript

angular.module('myapp',[])
.directive('someDirective',function(){
  return {
    restrict:'E',
    scope:{},
    link: function (scope,element,attrs) {

      //Code goes here

    }
  }
})
.directive('click-trigger',function($rootScope) {
  return {
    restrict:'E',
    link: function(scope,element,attrs) {

      element.bind('click',callBackFunction);

      function callBackFunction () {
        //callback
      }

    }
  }
})

Upvotes: 2

Views: 129

Answers (3)

Shashank
Shashank

Reputation: 2060

Using click event in directive makes a code loosely coupled with that of the controller being invoked. If there are multiple controllers associated and the same directive(s) getting used, then the code becomes redundant. So a smarter way is to define the click event in the AngularJS custom directives itself. Moreover, when interaction with DOM of AngularJS is concerned, which is not easy, so by this way, it paves the way for the same.

Upvotes: 0

Charlie
Charlie

Reputation: 23818

More angular way in my view is to include the nested elements in a template.

.directive('foo', function(){
                return {                 
                 template:'<button ng-click="clickMe()">Click Me</button>'               
                }                
            })

The problem of your approach is that the nested DOM elements belong to the scope of the directive - not to the scope of the controller. You can very easily run in to confusion if you are trying to create isolated scopes.

Please note that angular behaves in odd ways when it comes to isolated scopes. This is unnecessarily complicated in my view.

Please study this question.

Upvotes: 1

Voreny
Voreny

Reputation: 785

It's cleaner this way. Everything is separated, you don't mix javascript with HTML. This tendency is also perceivable in vanilla JS, where you don't set onclick attributes on elements, yet you addEventListener upon loading (or anywhere in the JS code).

Upvotes: 1

Related Questions