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();
}
}
});
添加回答
舉報