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

Javascript Angularjs在指令模板中引用子元素的最佳实践,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,假设您有如下指令模板: <div> <div> <div> <!--This is the element I want to reference--> <div></div> </div> </div> </div> 但这种方法似乎不是很有说服力 我应该使我想要引用子指令的元素进入父控制器吗

假设您有如下指令模板:

<div>
    <div>
        <div>
            <!--This is the element I want to reference-->
            <div></div>
        </div>
    </div>
</div>
但这种方法似乎不是很有说服力

我应该使我想要引用子指令的元素进入父控制器吗


或者我缺少的还有另一种方法在这里更有效吗?

如果你不能像class=“myclass”这样放置一个引用 看看

您也可以在不包含jquery库的情况下使用它

我会创建一个更“通用”的指令,以便它可以在任何地方重用: 这是一个扑克牌:

通用指令:

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>')
}
模板:

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>')
}

你好
您的指令:

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>')
}
链接:功能(范围){
//现在你已经在你的范围内了!
scope.hello.append('world!')
}

你能澄清一下你想对这个指令(和子元素)做什么吗?@Rob你能给我一个关于我的答案的反馈吗?@Rob如果你想分配一个点击处理程序,你可以在指令的模板中给它一个
ng click
属性,并在指令的作用域中指定一个函数。如果这是不可能的,那么我认为需要具体的建议你。