我正在尝试在指令之间创建一种通用切换功能,其中包含模板的一个指令不会呈现,直到从另一个指令发生事件。关于如何将它们联系在一起的任何建议?
谢谢!
答案 0 :(得分:2)
有很多方法可以实现这一目标。
使用事件(但要小心,如果过度使用,尤其是指令之间的交互,你很容易迷失!这就是为什么我没有为它创建http://plnkr.co,更糟糕的是:
$rootScope.$on('myEvent', function(e, eargs) {...})
主指令。$rootScope.$broadcast('myEvent', {foo: 'bar'})
。$rootScope
。angular.module('masterDirective', [])
.directive('masterDirective', function ($rootScope, $compile /**injects here*/) {
var templ = '<p ng-bind="someVar"></p>';
return {
restrict: 'EA',
scope: {},
link: function (scope, element, attrs) {
scope.someVar = "I am a template and I was born and visible to the world, because slaveDirective send me an event to do so.";
$rootScope.$on('myEvent', function(e, eArgs) {
// eArgs.myVar will be 'Jackson';
element.append($compile(templ)(scope));
});
}
}
});
angular.module('slaveDirective', [])
.directive('slaveDirective', function ($rootScope) {
return {
restrict: 'EA',
scope: {},
link: function (scope, element, attrs) {
$rootScope.$broadcast('myEvent', {myArg: 'Jackson'});
}
}
});
使用“共享控制器”是更简洁但更复杂的方式。这种方法的类型更强,你表达了工作流程,一旦它工作,它就不容易打破。
controller(scope,element,attrs) {...}
require: 'myMasterDirective'
<body ng-app="myApp">
<button ng-click="includeSlave=true">include slave directive</button>
<master-directive>
<div ng-if="includeSlave==true">
<slave-directive></slave-directive>
</div>
</master-directive>
</body>
angular.module('myApp', [])
.directive('masterDirective', function ($rootScope, $compile /**injects here*/) {
var templ = '<p ng-bind="someVar"></p>';
return {
restrict: 'E',
controller: function ($scope, $element) {
return {
slaveLink: function() {
$element.append($compile(templ)($scope));
}
}
},
link: function (scope, element, attrs) {
scope.someVar = "I am a template and I was born and visible to the world, because slaveDirective called a function on myself to do so.";
}
};
})
.directive('slaveDirective', function () {
return {
require: '^masterDirective',
restrict: 'E',
link: function (scope, element, attrs, myMasterController) {
myMasterController.slaveLink();
}
};
});