Angularjs在指令模板中引用子元素的最佳实践

时间:2014-01-27 15:57:27

标签: javascript angularjs angularjs-directive

假设你有一个这样的指令模板:

<div>
    <div>
        <div>
            <!--This is the element I want to reference-->
            <div></div>
        </div>
    </div>
</div>

我知道我可以像这样引用元素:

link: function(scope, element, attrs) {
   element.children().children().children....
}

但这种做法似乎并不十分雄辩。

我应该创建我想引用child指令的元素并传入父控制器吗?

或者是否有另一种方法可以让我在这里工作得更好?

2 个答案:

答案 0 :(得分:1)

我会创建一个更“通用”的指令,以便可以在任何地方重复使用:

这是一个吸虫:http://plnkr.co/edit/q5H8ydH73UB4TtOtGT1r?p=preview

通用指令:

app.directive('ref',function(){
  return {
    link: function(scope,el,attrs){
      scope[attrs.ref] = el;

      // we should clean up to avoid memory leaks        
      el.on('$destroy',function(){
        scope[attrs.ref] = null;  
      });
    }
  }
})

<强>模板:

<div>
    <div>
        <div>
            <!--This is the element I want to reference-->
            <div ref="hello">
              hello
            </div>
        </div>
    </div>
</div>

您的指示:

link: function(scope){
  // now you have it on your scope!
  scope.hello.append('<span> world !</span>')
}

答案 1 :(得分:0)

如果你不能把类似class =“myclass”的引用 看看

http://api.jquery.com/eq/

您也可以使用它而不包含jquery库

http://docs.angularjs.org/api/angular.element