3 回答
TA贡献1818条经验 获得超8个赞
在您的示例中,指令结构不是父子结构。因此,您无法通过其控制器共享方法。我会用$rootScope.$broadcast。(请参阅DOCS)
一个指令调用:
$rootScope.$broadcast('someEvent', [1,2,3]);
第二条指令侦听:
scope.$on('someEvent', function(event, mass) {
console.log(mass)}
);
固定指令:
app.directive("firstDir", function ($rootScope) {
return {
restrict: 'E',
link: function (scope, element, attrs) {
scope.dataToPass = 'empty';
scope.doClick = function (valueToPass) {
scope.dataToPass = valueToPass;
$rootScope.$broadcast('someEvent', {
data: valueToPass
});
}
}
};
});
app.directive("secondDir", function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
scope.receivedData = 'none';
scope.$on('someEvent', function (event, result) {
scope.receivedData = result.data;
});
}
}
});
TA贡献1951条经验 获得超3个赞
我正在使用的是导出指令控制器。假设我有以下指令:
app.directive('mainDirective', function () {
return {
require: 'mainDirective'
restrict: 'E',
scope: {
controller: '='
},
controller: [
'$scope',
function ($scope) {
// controller methods
this.doSomething = function () { ... },
$scope.controller = this
return this
}
],
link: function (scope, element, attrs, mainDirective) {
// some linking stuff
}
}
});
我的html看起来像这样:
<main-directive controller="mainDirective"></main-directive>
<sub-directive main-directive="mainDirective"></sub-directive>
如果我想从子指令控制主指令,我可以轻松地从它的作用域中获取它并做我想做的任何事情...
app.directive('subDirective', function () {
return {
restrict: 'E',
scope: {
mainDirective: '='
}
link: function (scope, element, attrs) {
// do something with main directive
scope.mainDirective.doSomething();
}
}
});
添加回答
举报