Angularjs:如何将作用域变量传递给指令?

27

我正在尝试使用指令来创建并附加多个标签到一个 <div> 中,如下所示:

module.directive('createControl', function(){
  return function(scope, element, attrs){    
    console.log(attrs.createControl); // undefined     
  }                                          
});                                         


<div class="control-group" ng-repeat="(k, v) in selectedControls">
  <div create-control="{{ v.type }}"></div>
</div>

在attrs中我有这个结构:

$$element: b.fn.b.init[1]
$$observers: Object
$attr: Object
createControl: "date"
style: "margin-right: 15px"
__proto__: Object

但是当我尝试使用attrs.createControl时,我得到了undefined,我不明白为什么。实际问题是:如何将作用域变量传递给指令?

3个回答

34
    app.directive('createControl', function() {
      return {
        scope: {
          createControl:'='
        },
        link: function(scope, element, attrs){    
           element.text(scope.createControl);    
        }      
      }
    })  

  <div class="control-group" ng-repeat="v in [{type:'green'}, {type:'brown'}]">
    <div create-control="v.type"></div>
   </div>

我不太确定我理解这个问题,它怎么知道 div 是指令? - Jackie
5
Angular会查找与create-control(连字符分隔的小写)属性匹配的指令(驼峰式命名)。 - isherwood
1
以下是有关编程的内容,请将其从英语翻译成中文。 返回仅翻译的文本:解释,希望有所帮助:1.) '@' 由于某种原因无法使用。2.)还可以使用多个变量进行应用,例如 <create-control val1="v.type" value-two="x.y"></create-control>。请注意,指令范围定义(valueTwo)中的value-two也会变为驼峰命名法。3.) 变量周围不能有{{}}(例如,没有...="{{v.type}}")。 - phil294

15

阅读指令文档中的属性/观察插值属性部分。在链接阶段,属性尚未设置。

有多种方法,包括使用attrs.$observe$timeout

app.directive('createControl', function($timeout){
 return function(scope, element, attrs){
      attrs.$observe('createControl',function(){
        console.log(' type:',attrs.createControl);
         element.text('Directive text, type is: '+attrs.createControl);
      });
  }
}) ;

演示


15

如果v.type可能会改变(即你确实需要使用插值--{{}}),那么你可以根据想要的作用域类型选择@charlietfl或@Joe的答案。

如果v.type不会改变(即您的链接函数只需要获取一次值,并且这些值在链接函数运行时保证已设置),则可以使用$parse$eval。这具有轻微的性能优势,因为不会创建任何$watches。(对于$observe()=,Angular设置$watches,这些$watches在每个digest循环中进行评估。)

<div create-control="v.type"></div>
app.directive('createControl', function ($parse) {
    return function (scope, element, attrs) {
        console.log('$eval type:', scope.$eval(attrs.createControl));
        var type = $parse(attrs.createControl)(scope);
        console.log('$parse type:', type);
        element.text('Directive text, type is: ' + type);
    }
});

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接