目标:使用指令创建行为,并在 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>
我知道将内容放在文章指令中会更容易,但是这个问题是要找出如何解决这样的情况。
内容指令能否以某种方式将自身传递给相关的文章指令?
这段代码不像现在这样有用,但它是一个起点。我将如何做到这一点?
.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.
}
}
}