AngularJS Question

executing angular functions

i have a html button like this

<md-button type="button" ng-click="commentDelete(item,$index)" aria-label="change address" >
<md-icon md-svg-icon="img/ic_highlight_remove_24px.svg"></md-icon>
</md-button>


this is my controller

var commentDelete = function(item,index){
console.log('working')
}

$scope.commentDelete =commentDelete;


this is working without any problem.
but if i try something like this

var myCtrl= function(item,index){
return {
commentDelete : function(item,index){
console.log('working')
}
}
}

$scope.commentDelete =myCtrl.commentDelete


then it doesn't trigger the commentDelete function. why is that? thanks in advance

Answer

Because you assign to the $scope.commentDelete a property of the myCtrl(myCtrl is a function, and it tries to find a commentDelete on it or in the Function). myCtrl is only a function, which returns an object with the function commentDelete.

var myCtrl= function(item,index){
   return {
      commentDelete : function(item,index){
        console.log('working')
      }
   }
} 

 $scope.commentDelete = myCtrl.commentDelete

If you call myCtrl and then get the commentDelete, it will work

$scope.commentDelete = myCtrl().commentDelete;
Comments