我正在尝试构造一个 sub 指令,稍后将在多个指令中使用。
这些父指令有相同的 Controller ,它提供了一些方法,我想用这些方法更新这些指令范围内的东西:
(以后可能会使用不同的 Controller ,但使用这些相同的通用方法)
myApp
.controller('SomeCommonController', function() {
this.someMethod = function(data) {
// do something for updating scope variables
}
...
return this;
})
.directive('myDir1', function() {
return {
controller: 'SomeCommonController',
template : '<sub-dir ng-repeat="sth in aList" data="sth"></sub-dir>',
...
}
})
.directive('myDir2', function() {
return {
controller: 'SomeCommonController',
template : 'Something Different with calling <sub-dir data="otherData"></sub-dir>',
...
}
})
.directive('subDir', function() {
return {
scope: { data : "=" }
require: "^something", // parent directive
template: '<button ng-click="someMethod(data);"></button>'
link: function(scope, elem, attrs, parentDirectiveCtrl) {
scope.someMethod = function(data) {
parentDirectiveCtrl.someMethod(data);
};
},
...
}
})
有没有办法只要求调用者指令的 Controller ?或者是否有更好的方法来实现相同的行为?
最佳答案
我不认为有任何方法可以动态地找到谁是父 Controller (我的意思是说父指令)
我建议您将 require 与数组一起使用,这意味着在数组中提及您的 require 字段,就像这里 require 会 require: ['?^^myDir1', '?^^myDire2']
然后在链接函数中第 4 个参数是 Controller 的,如果你 ctrl[0]
你可以获得 myDir1
的 Controller ,如果你这样做 ctrl[1]
然后你会得到 myDir2
You must use
?^^
because there could be one of them would not present in parent of directive
.directive('subDir', function() {
return {
scope: { data: "=" },
require: ['?^^myDir1', '?^^myDir2'], // parent directive
template: '<button ng-click="someMethod(data);"></button>'
link: function(scope, elem, attrs, parentDirectiveCtrl) {
if(parentDirectiveCtrl[0])
console.log('Parent controller is myDir1')
if(parentDirectiveCtrl[1])
console.log('Parent controller is myDir2')
//whenever you want to call method of parent directive
//then you should use either parentDirectiveCtrl[0] for myDir1
//or parentDirectiveCtrl[1] for myDir2
scope.someMethod = function(data) {
parentDirectiveCtrl[0].someMethod(data);
};
},
...
}
})
关于javascript - 根据 AngularJS 中的父指令,子指令中的“require”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29992687/