[英]Angular ng-repeat with bootstrap input checkbox with dynamic ng-model using ng-true-value
這個問題對我來說有點棘手,所以我會盡力而為。 我正在嘗試使用動態ng-model正確正確地使用ng-true-value實現Angular復選框。
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-repeat="asset in asset">
<h5>{{ asset.title }} categories are...{{ asset.category[0] + " and " + asset.category[1] }}</h5>
<div class="form-group">
<label>Business</label>
<div class="checkbox" ng-repeat="category in categoryFactory.business">
<input type="checkbox" id="{{category}}" ng-true-value="{{'category'}}" ng-model="asset.category[$index]">
<label for="{{category}}">{{category}}</label>
</div>
</div>
<div class="form-group">
<label>Personal</label>
<div class="checkbox" ng-repeat="category in categoryFactory.personal">
<input type="checkbox" id="{{category}}" ng-true-value="{{'category'}}" ng-model="asset.category[$index]">
<label for="{{category}}">{{category}}</label>
</div>
</div>
</div>
</div>
我的最終目標是,當我加載資產(在下面找到...)時,它將顯示為“ 我的最終目標 ”圖片,並選中了正確的復選框。 業務和個人類別是從工廠派生的,每個表單組復選框都來自工廠中“業務/個人”的ng-repeat列表。
$scope.asset = [{
title: "Sales Agreement",
category: ["finance-admin", "running-a-business"]
}];
我的問題是必須在復選框內正確實現ng-model。 由於每個資產可以具有1個或多個類別,因此需要動態。 我嘗試使用$ index使我的ng模型動態...
ng-model="asset.category[$index]"
但這似乎不像我希望的那樣工作。 我可能缺少一些非常簡單的東西,將不勝感激。
謝謝! 順便說一下,這里是JSFIDDLE
當前,按照您的$ index邏輯,兩個數組categoryFactory.business
和asset.category
的大小必須相同,因此這是更新的jsfiddle
但主要的是
首先,對於您的情況,ng-true-value應該是一個表達式
ng-true-value="{{category}}"
其次,您的asset.category
數組索引應與categoryFactory.business
數組中的選項匹配
$scope.asset = [{
title: "Sales Agreement",
category: ["", "running-a-business","", "","finance-admin"]
}];
有一個更好的選擇可以在不依賴$ index的情況下進行管理,但這應針對您的情況
我使用ng-checked,可以將函數作為屬性值,ng-repeat將在每個循環中評估函數。
<input type="checkbox" id="{{category}}" ng-checked="isCategory(category)" >
$scope.isCategory = function(category){
return $scope.asset[0].category.indexOf(category) >= 0;
}
在isCategory()中,我們正在檢查asset.category數組中類別的索引(如果找到的話)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.