使用Angular更改JSON中存储的布尔值

Changing a boolean stored in JSON with Angular?

本文关键字:存储 布尔值 JSON Angular 更改 使用      更新时间:2023-09-26

当用户单击填充有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;
};

首先进行一些更正。

  1. 请参阅$scope.prices中的阵列Prices

  2. 更改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>

乐于助人!