2013-09-23 54 views
0

我想爲我的角度應用製作定製驗證指令。唯一的問題是,我不知道如何獲得一個價值角度定製驗證指令

<select class="form-control" ng-model="$parent.newSector" ng-options="item.id as item.name for item in sectors" not-empty-array="merchant.sectors"></select> 

你可以從我的標記我有叫notEmptyArray這裏我設置一個表達式的指令看到(這是一樣的NG-模型,只是一個不同的表達)。我現在如何在我的指令中訪問它?

directive = function({ 
    require: "ngModel", 
    link: function(scope, element, attributes, control) { 
    //how to access the value of merchant.sectors (its an array in the scope) 
    } 
}); 
+0

'scope.merchant.sectors'? – AlwaysALearner

+0

是的,我可以這樣做,但「merchant.sectors」的一部分需要設置非空數組的值。所以如果我寫用戶作爲這個屬性的值。它應該檢查scope.users – Safari

回答

1

您將需要範圍隔離:

app.directive("notEmptyArray",function(){ 
    return { 
     scope:{ 
      items:"=notEmptyArray" 
     }, 
     link: function(scope, element, attributes, control) { 
      /* anything you feed to "not-empty-array" would be accessible 
       inside items */ 
      console.log(scope.items);  
     } 
    } 
}); 
+0

thx。工作 – Safari

+0

隔離作用域的缺點是,如果其他指令綁定到來自父作用域(頻繁場景)的某些內容,則其他指令將不再與您的指令一起工作。原因是一個html元素只能有一個範圍。如果多個指令需要一個範圍,則只會創建一個(最嚴格的指令)。您需要確保您的指令與其他指令兼容,以重新展示您的隔離範圍內的某些屬性。我建議你不要去那個方向,只需要做一個:「scope。$ eval(attrs.notEmptyArray)來獲得值。 –