3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
在您的示例中,指令結(jié)構(gòu)不是父子結(jié)構(gòu)。因此,您無(wú)法通過(guò)其控制器共享方法。我會(huì)用$rootScope.$broadcast。(請(qǐng)參閱DOCS)
一個(gè)指令調(diào)用:
$rootScope.$broadcast('someEvent', [1,2,3]);
第二條指令偵聽(tīng):
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貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
我正在使用的是導(dǎo)出指令控制器。假設(shè)我有以下指令:
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看起來(lái)像這樣:
<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();
}
}
});
添加回答
舉報(bào)