2

Hi I am new to Angular and trying out the directives. Following is the code

HTML

<div ng-app="scopetest" ng-controller="controller">
  <div phone action="callhome()"> </div>
</div>

javascript

angular.module("scopetest", [])
.controller("controller", function($scope){
  $scope.callhome = function(){
    alert("called");
  }
})
.directive("phone", function(){
  return {
    scope: {
      action:"&"
    },
    template: "<button ng-click='action()' >Call</button>"
  };
});

My question is if we are passing the callhome function to the action attribute, and on ng-click we are calling the action function with parenthesis, then why do we need to specify the parenthesis while setting the attribute on phone directive ng-click='action()'? Why doesn't just ng-click='action' work? We are already specifying action="callhome()". Why needed at both places?

sidgate
  • 14,650
  • 11
  • 68
  • 119

1 Answers1

4

Because the attribute doesn't specify a function. It specifies an expression. Most of the time you want that expression to be a function call (and function calls need () (or apply or new or etc).

You could specify something else instead:

ng-click="window.myGlobal = true;"
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • thanks. Does this means that this also applies to my directive `action="callhome()"`. why not `action="callhome"` ? – sidgate Aug 26 '16 at 17:32