目标:使用指令创建行为,并在 2 个兄弟元素(每个元素都有自己的指令)之间进行通信。
示例中使用的行为:默认情况下隐藏文章内容。当点击标题时,我希望显示相关的文章内容。
问题:相关的文章元素需要相互关联,而不是嵌套在单个父元素或指令中。
<div article="article1">this is my header</div>
<div id="article1" article-content>this is content for the header above</div>
<div article="article2">this is my header</div>
<div id="article2" article-content>this is content for the header above</div>
我知道将内容放在article指令中会更容易,但是这个问题是为了找出如何解决这样的情况。
内容指令能否以某种方式将自身传递给相关的文章指令?
这段代码不像现在那么有用,但它是一个起点。我该如何实现这个目标?
.directive('article', function(){
return {
restrict: "A",
controller: function($scope) {
$scope.contentElement = null;
this.setContentElement = function(element) {
$scope.contentElement = element;
}
},
link: function(scope, element) {
element.bind('click', function(){
// Show article-content directives that belong
// to this instance (article1) of the directive
}
}
}
}
.directive('articleContent', function(){
return {
require: "article",
link: function(scope, element, attrs, articleCtrl) {
// Maybe reference the article i belong to and assign element to it?
// I can't though because these are siblings.
}
}
}
最佳答案
指令 require
选项都不允许您要求同级指令(据我所知)。您只能:
- 对元素进行 require,使用
require: "directiveName"
- 告诉 Angular 使用
require: "^directiveName"搜索 DOM 树
- 或
require: "^?directiveName"
(如果您不一定需要父 Controller ) - 或
require: "^\?directiveName"
如果您不一定需要父 DOM 包装器
如果您想要 sibling 之间的通信,则必须将它们放置在某个父 DOM 元素中,并使用指令 Controller 充当其通信的 API。如何实现在很大程度上取决于当前的上下文。
这是 Angular JS (O Reilly) 中的一个很好的例子
app.directive('accordion', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
template: '<div class="accordion" ng-transclude></div>',
controller: function() {
var expanders = [];
this.gotOpened = function(selectedExpander) {
angular.forEach(expanders, function(expander) {
if(selectedExpander != expander) {
expander.showMe = false;
}
});
};
this.addExpander = function(expander) {
expanders.push(expander);
}
}
}
});
app.directive('expander', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
require: '^?accordion',
scope: { title:'@' },
template: '<div class="expander">\n <div class="title" ng-click="toggle()">{{ title }}</div>\n <div class="body" ng-show="showMe" \n ng-animate="{ show: \'animated flipInX\' }"\n ng-transclude></div>\n</div>',
link: function(scope, element, attrs, accordionController) {
scope.showMe = false;
accordionController.addExpander(scope);
scope.toggle = function toggle() {
scope.showMe = !scope.showMe;
accordionController.gotOpened(scope);
}
}
}
})
用法( Jade 模板):
accordion
expander(title="An expander") Woohoo! You can see mme
expander(title="Hidden") I was hidden!
expander(title="Stop Work") Seriously, I am going to stop working now.
关于angularjs - 与兄弟指令沟通,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18245388/