簡體   English   中英

Angularjs:如何將范圍變量傳遞給指令?

[英]Angularjs: how to pass scope variables to a directive?

我正在嘗試使用指令來創建和附加幾個標簽到<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 ,我不明白為什么。 實際問題:如何將范圍變量傳遞給指令?

    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>

讀取指令文檔的 屬性/觀察插值屬性部分。 在鏈接階段,尚未設置屬性。

有幾種方法,包括使用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);
      });
  }
}) ;

DEMO

如果v.type可能會改變(即,您確實需要使用插值 - {{}} s),請使用@ charlietfl或@ Joe的答案,具體取決於您希望指令具有的范圍類型。

如果v.type不會改變(即,你的鏈接函數只需要獲取一次值,並且保證在鏈接函數運行時設置這些值),你可以使用$ parse$ eval代替。 這有一個輕微的性能優勢,因為沒有創建$ watch。 (使用$observe()= ,Angular設置$ watch,每個摘要周期都會對其進行評估。)

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

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM