AngularJS:在另一个指令中使用一个指令中设置的属性

时间:2015-11-10 08:56:19

标签: angularjs angularjs-directive

方案

假设我有两个指令firstsecond,其中指令用于相同的 DOM元素:

HTML

<div first second></div>

的Javascript

//first directive
.directive('first', function(){
return {
    restrict: 'A',
    priority: 1,
    link: function(scope, element, attrs){
        element.attr('someAttr', 1234);
        element.html('I have the attribute value: ' + element.attr('someAttr'));
       }
   };
})
// second directive
.directive('second', function(){
return {
    restrict: 'A',
    priority: 0,
    controller: function($scope, $element, $attrs){
        // the elements attribute `someAttr` is undefined here
    }
   };   
})

first指令将属性(someAttr)添加到正在使用它的元素中。

问题

我想要实现的是访问/使用 someAttr指令的链接/控制器功能中first directive的设置值(在second中设置) 。但就目前而言,我没有成功。 (Check this fiddle out

注意:我还将first指令的优先级设置为高于second的值,但是当您记录元素的属性时仍然如此在使用该指令的地方,集合中没有someAttr属性。

还要注意,如果我想如何实现指令之间的通信是不合适的,那么这样做的正确方法是什么?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您无法直接检测设置到DOM元素的属性的更改(至少不能以angularjs方式)。

尝试在第一个指令控制器中使用属性,然后要求&#39; &#39;第一&#39;在第二个&#39;访问第二个&#39;属性。

查看有关&'39;要求&#39;的信息。定义指令以查看其工作原理时的属性。

更新:检查这个plunkr:

http://plnkr.co/edit/bEbO8LvCIUd0NZPFqMnv?p=preview

app.directive('first', function(){
return {
    restrict: 'A',
    link: function(scope, element, attrs){
        element.html('I (first) have the scope value: ' + scope.data.attribute);
       },
       controller: function($scope) {
         this.data = $scope.data = {
           attribute: 1234
         };
       }
   };
});
// second directive
app.directive('second', function(){
return {
    restrict: 'A',
    require: 'first',
    priority: 1,
    link: function($scope, element, attrs, firstController){
        element.html(element.html() + ' and I (second) have access to that value too: ' + firstController.data.attribute);
        //you can $scope.$watch firstController.data changes here too
    }
   };   
});
相关问题