执行角函数

executing angular functions

本文关键字:函数 执行      更新时间:2023-09-26

我有一个像这样的HTML按钮

<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>

这是我的控制器

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

这个工作没有任何问题。但是如果我尝试这样写

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

则不会触发commentDelete函数。为什么呢?提前感谢

因为您将myCtrl的属性分配给$scope.commentDelete (myCtrl是一个函数,它试图在其上或Function中找到commentDelete)。myCtrl只是一个函数,它返回一个函数为commentDelete的对象。

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

如果你调用myCtrl,然后得到commentDelete,它将工作

$scope.commentDelete = myCtrl().commentDelete;