angularjs控制器将函数传递给具有隔离范围的指令中的指令

时间:2015-05-25 05:58:35

标签: angularjs function hierarchy directive

是否有人试图将父控制器函数传递给内部指令(指令内的指令)?

这是我尝试做的方式(我已经删除了不相关的行):

angular.module('myHeaven').controller('forrestController',function($scope)
{
    $scope.notifyCallback=function(notificationData){
        console.log('It is Adam again: ' & notificationData);
    }
});

angular.module('myHeaven').directive('tree',function($scope){
    return {
        scope:{notification:'&'}
    }
});

angular.module('myHeaven').directive('apple',function($scope){
return {
    scope:{
     notification:'&'
    },
    template:'<input type="button" ng-click="pick()" >bite Me</button>'
    controller:function($scope){
    $scope.pick=function(){
     $scope.notification({notificationData:'apple picked'});    
    }
 }
}
});

heaven.html

<div tree notification="notifyCallback(notificationData)">
    <div apple notification="notifyCallback(notificationData)">
    </div>  
</div>

调用forrestController中的$ scope.notification,但不传递任何参数。

2 个答案:

答案 0 :(得分:0)

您需要在树指令上使用transclusion,或者您可以在树的模板中编写其他指令。 只要对其使用包含,您就不需要将该方法传递给树指令。 并且你将$ scope传递给指令工厂函数,这导致了错误。在控制器上传递$ scope。在指令范围作为链接函数的第一个参数传递。 查看我的plunker

  <div tree >
    <div apple notification="notifyCallback(notificationData)"></div>  
  </div>


angular.module('myHeaven', []);

angular.module('myHeaven')
      .controller('forrestController',function($scope) {
          $scope.notifyCallback=function(notificationData) {
              console.log('It is Adam again: ' + notificationData);
    };
});

angular.module('myHeaven').directive('tree',function(){
    return {
      transclude: true,
      template: '<div class="tree"><ng-transclude></ng-transclude></div>',
        scope:{}
    };
});

angular.module('myHeaven').directive('apple',function(){
return {
    scope:{
     notification:'&'
    },
    template:'<input ng-click="pick()" type=button>bite Me</button>',
    controller:function($scope){
    $scope.pick=function(){
     $scope.notification({notificationData:'apple picked'});    
    };
 }
};
});

答案 1 :(得分:0)

终于找到了答案,......只是一种语法。

<div tree notification="notifyCallback({notificationData:notificationData})">
    <div apple notification="notifyCallback({notificationData:notificationData})">
    </div>  
</div>
相关问题