[英]Changing a boolean stored in JSON with Angular?
我試圖在用戶單擊使用JSON填充的表行時更改布爾值。 比如我有這個......
$scope.prices = {
"Prices": [
{
"Code": "edl",
"Selected": false
},
{
"Code": "ead",
"Selected": false
}
]
}
然后我綁定到一個表...
<table>
<tr ng-click="change(item.code)" ng-repeat="item in prices">
<td>{{prices.Code}}</td>
</tr>
</table>
當用戶點擊一行時,會觸發更改功能,然后將所選值更改為true或false
$scope.change = function (itemCode) {
//update the clicked code selcted value to True/False
// first check if its true or false
// then change it accordingly
// Please excuse my terrible attempt!
if(!$scope.prices.code.selected){
$scope.prices.code.selected = true
} else {
$scope.prices.code.selected = false
}
};
因為我不確定如何通過更改功能實現此目的。 或者還有另一種方式嗎? 謝謝
首先,在到達實際的價格數組之前,在$scope.prices
有一個額外的級別是沒有多大意義的。
換句話說,而不是:
$scope.prices = {
"Prices": [
{
"Code": "edl",
"Selected": false
},
// etc.
]
};
你應該直接使用數組,這樣你就可以輕松地綁定它:
$scope.prices = [
{
"Code": "edl",
"Selected": false
},
// etc
];
然后你可以像這樣綁定它:
<table>
<tr ng-click="change(item)" ng-repeat="item in prices">
<td>{{item.Code}}</td>
</tr>
</table>
最后,現在$scope.change()
獲取整個項目,而不僅僅是代碼,您可以直接切換其Selected
屬性:
$scope.change = function (item) {
item.Selected = !item.Selected;
};
首先是一些修正。
請參閱$scope.prices
的數組Prices
。
更改change()
的簽名,以便獲取對所單擊項的引用。
<table> <tr ng-click="change(item)" ng-repeat="item in prices.Prices"> <td>{{item.Code}}</td> </tr> </table>
現在實現更改方法
$scope.change = function (item) { if (item.Selected) { item.Selected = false; } else { item.Selected = true; } };
這是另一個沒有涉及函數的清潔解決方案,如果您對內存使用情況謹慎,這種方法將使您無法從$ scope中刪除函數。
<table>
<tr ng-click="item.Selected = !item.Selected" ng-repeat="item in prices">
<td>{{item.Code}}</td>
</tr>
</table>
快樂幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.