2013-11-02 39 views
0

我創建在角一個指令,其中其範圍不是孤立的引用在$範圍的對象AngularJS字符串轉換爲對象/陣列

<div ng-controller="myController"> 
    <ul> 
     <li myDirective="model[1].list" >a lot more things will happen inside here</li> 
    </ul> 
</div> 

CONTROLLER:

app.controller("myController",["$scope",function($scope){ 
$scope.model = [ 
     { 
      list:[ "object1","object2","object3" ] 
     }, 
     { 
      list:[ "object4","object5","object6" ] 
     }, 
     { 
      list:[ "object7","object8","object9" ] 
     } 
    ] 
}]); 

指令:

app.directive("myDirective",[function(){ 
    return { 
     scope:true, 
     controller:function($scope,$element,$attrs){ 
      /* 
       How do I directly be able to manipulate from inside here what is assigned 

on the $attrs.myDirective 

without ISOLATING the scope of the directive 

        */ 
      } 
     } 

    }]); 

我使用的解決方案之一是這個函數,我把它放在指令中,並將字符串處理爲簽署到$ attrs.myDirective它適用於「model.list」 ,但與「模型[2] .list」它並不是因爲它沒有爲它構建。如何修改這個功能還是有這個問題更好的解決方案...

$scope.rediks = function(string) 
    {   
     var scope = $scope; 
     var scopeSplit = string.split('.'); 
     for (i = 0; i < scopeSplit.length - 1; i++) 
     { 
      scope = scope[scopeSplit[i]]; 
      if (scope == undefined) return; 
     } 
     return scope[scopeSplit[scopeSplit.length - 1]]; 
    } 

非常感謝你,

回答

6

使用$parse服務(docs)來獲取值由屬性指出:

controller: function($scope,$element,$attrs,$parse) { 
    var value = $parse($attrs.myDirective)($scope); 
    // for the above case, value = [ "object4","object5","object6" ] 
}