2014-12-01 113 views
-2

是否可以在AngularJS中爲ng模型添加增量標識符?AngularJS添加增量值

我正在遍歷項目列表,並需要和循環中每個項目的ng-model =「」屬性的增量值,或者如果有更簡單的方法,我希望聽到它。

什麼我目前正在:

  <li ng-repeat="recipe in recipes"> 
       <label for="cost_ingredient_{{recipe.ingredient_id}}" style="font-size: 16px;">{{recipe.ingredient}}</label> 
       <input ng-model="{{recipe.model_name}}" name="formcost_ingredient_{{recipe.ingredient_id}}" type="number" id="cost_ingredient_{{recipe.ingredient_id}}" min="0" step="0.01" value="0" /> 
      </li> 

我試圖用一個指令,這樣做,但是當我稱之爲「FORMDATA」在控制器中,沒有一個模型指標上來。

我需要將這些信息作爲表單提交的一部分返回到流程中的下一頁。這將部署到Android,所以我想只是將其添加到window.sessionStorage,因爲我只需要這一次每次用戶運行我的應用程序。

回答

0

迭代的,在NG-INIT中繼器連接的ID。這將修改您的原始結構,並且該ID將在中繼器之外提供。

<li ng-repeat="recipe in recipes" > 
    <label ng-init="recipe.someId = $index" for="cost_ingredient_{{recipe.someId}}" > 
     {{recipe.ingredient}} 
    </label> 
    <input ng-model="{{recipe.model_name}}" name="formcost_ingredient_{{recipe.someId}}" 
      type="number" id="cost_ingredient_{{recipe.someId}}" 
      min="0" step="0.01" value="0" /> 
</li> 

這類似於米哈爾Stefanow的答案,但在這裏,你實際上是通過添加一個屬性的每個項目,在這種情況下,它被稱爲改變結構someId

另一種方式:

<li ng-repeat="recipe in recipes" > 
    <label ng-init="recipe.costIngredient = 'cost_ingredient_' + $index" for="{{recipe.costIngredient}}" > 
     {{recipe.ingredient}} 
    </label> 
    <input ng-model="{{recipe.model_name}}" 
      ng-init="recipe.formcostIngredient = 'formcost_ingredient_' + $index" name="{{recipe.formcostIngredient}}" 
      type="number" id="{{recipe.costIngredient}}" 
      min="0" step="0.01" value="0" /> 
</li> 

您真正想要的是在JavaScript端對其進行預處理,以免它每次都被評估:

$scope.recipes = [ your array here ]; 

angular.forEach($scope.recipes, function(recipe, index){ 

    recipe.costIngredient = 'cost_ingredient_' + index; 
    recipe.formcostIngredient = 'formcost_ingredient_' + $index; 

}); 

然後迭代。

P.S.您可能需要考慮使用ng-bind而不是{{}}來生成HTML,這對於無法預料的錯誤會更好