[英]How can I access the function in child directive which passed from parent directive but defined in controller?
我有一个父指令和一个子指令,都在控制器中,视图在这里:
<body ng-app="myApp">
<section ng-controller="TestController">
<section parent-directive parentFn="callback">
<child-directive>
<button ng-click="save()">save</button>
</child-directive>
</section>
</section>
</body>
我想访问回调函数,该函数在TestController
中定义,但传递给parentDirective,然后传递给childDirective。
我的js代码:
var myModule = angular.module('myApp', []);
myModule.controller('TestController', function($scope) {
$scope.callback = function(){
console.log('callback invoked');
};
});
myModule.directive('parentDirective',function(){
return {
restrict: 'EA',
scope: {
parentFn: '&'
},
controller: function($scope){
this.parentFn = $scope.parentFn;
}
}
});
myModule.directive('childDirective',function(){
return {
restrict: 'EA',
require: '?^parentDirective',
transclude: true,
template: '<div ng-transclude></div>',
link: function(scope, element, attrs, controller){
console.log("child:c:%o",controller);
scope.save = function(){
console.log('save fn invoked');
console.log('is parentFn type:%o',typeof controller.parentFn);
controller.parentFn();
}
}
}
});
这是一个jsfiddle: https ://jsfiddle.net/savokiss/j6gp720c/
当我单击按钮时, callback invoked
的callback invoked
不会出现在控制台中。
为什么?
您没有在指令元素中正确传递函数,指令属性名称应为小写,然后将大写字母转换为小写并带有前缀连字符。 像这里parentFn
应该是parent-fn
,然后它的值应该具有方法调用。
<section parent-directive parent-fn="callback()">
<child-directive>
<button ng-click="save()">save</button>
</child-directive>
</section>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.