2013-07-31 28 views
15

我試圖做這樣的事情:角NG-重複表達式作爲變量

<ul> 
    <li ng-repeat="{{myRepeatExpression}}">{{row.name}}</li> 
</ul> 

但由於ng-repeat邏輯在該指令的編譯狀態時,它對待{{myRepeatExpression}}作爲一個正常的字符串,而不是一個變量。很明顯,這不起作用。

有沒有解決方法?

回答

10

您只能使用和表達ng-repeat而不是interpolated的值。 現在,爲了創建一個動態的可重複的列表,你可以嘗試兩種:

  1. 使用動態返回在ng-repeat列表中的功能 - 這是潛在的更昂貴,因爲角度的需求來調用函數第一,然後確定做一個$digest週期
  2. $watch爲觸發列表的變化範圍特定變量集合時發生了變化 - 可能更爲高效,但如果你的動態列表取決於多個可變它可以得到更詳細的和可能導致忘記添加新的潛在錯誤$watch需要新的變量時

Demo plunker

JS:

app.controller('MainCtrl', function($scope) { 
    var values1 = [{name:'First'}, {name:'Second'}]; 
    var values2 = [{name:'Third'}, {name:'Fourth'}, {name:'Fifth'}]; 

    //1. function way 
    $scope.getValues = function(id) { 
    if(id === 1) { 
     return values1; 
    } 
    if(id === 2) { 
     return values2; 
    } 
    } 

    //2. watch way 
    $scope.values = undefined; 
    $scope.$watch('id', function(newVal) { 
    $scope.values = $scope.getValues(newVal); 
    }); 
}); 

HTML:

<!-- Here we pass the required value directly to the function --> 
<!-- this is not mandatory as you can use other scope variables and/or private variables --> 
<ul> 
    <li ng-repeat="v in getValues(id)">{{v.name}}</li> 
</ul> 
<!-- Nothing special here, plain old ng-repeat --> 
<ul> 
    <li ng-repeat="v in values">{{v.name}}</li> 
</ul> 
2

ng-repeat只接受它專有的表達式語法,如row in rows,但rows可能是控制器中的函數或承諾。但是你需要仔細觀察性能,因爲ng-repeat不適用於變化頻繁的事情(可怕的最大迭代錯誤)。

+1

謝謝,我知道的語法,但如果你想將表達式存儲在變量? – Gilad

+0

如果它只是一個未評估的(DOM-)字符串(通過$ parse或$ scope。$ eval),那麼就沒有辦法做到這一點。 –

2

不能使用NG-RE使用應該直接表示表達式的字符串/變量進行泥炭化,但是可以創建插入/解析此值並將其傳遞給ng-repeat參數並重新編譯該元素的指令。

app.directive('ngVarRepeat',function($compile){ 
    return { 
    priority:1001, //must be higher than 1000 (priority of ng-repeat) 
    compile:function($elm,$attrs){ 

     var expression = $attrs.ngVarRepeat; 
     $elm.removeAttr('ng-var-repeat'); // remove attribute so we can recompile it later 

     return function(scope,elm,attrs){ 
     $elm.attr('ng-repeat',scope.$eval(expression)); 
     $compile($elm)(scope); 
     } 
    } 
    } 
}) 

在這個plunker看看:demo plunker from accepted answer

也請注意,這種做法應該引起嵌套NG-重複的煩惱。