javascript - 使用 Angular 更改存储在 JSON 中的 bool 值?

标签 javascript json angularjs

当用户单击填充有 JSON 的表行时,我试图更改 bool 值。例如我有这个...

$scope.prices = {
"Prices": [
    {
        "Code": "edl",
        "Selected": false
    },
    {
        "Code": "ead",
        "Selected": false
    }
]
}

然后我将其绑定(bind)到一个表...

<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.
]
};

你应该让数组直接向上,这样你就可以很容易地绑定(bind)到它:

$scope.prices = [
    {
        "Code": "edl",
        "Selected": false
    },
    // etc
];

然后你可以像这样绑定(bind)它:

<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;
};

关于javascript - 使用 Angular 更改存储在 JSON 中的 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28838533/

相关文章:

javascript - Google Maps API 路线服务以 xml 格式返回路线

javascript - AngularJS 和使用哈希 URL 的 js/css 库

javascript - Jquery cookie 总是返回 1

javascript - 保存 FCM 数据库消息的时间戳

javascript - Angular JS 没有正确编码 JSON 以传递 get 请求?

json - 使用 Jolt 从第一个数组元素中提取值

javascript - 将 Angular Directive(指令)模板绑定(bind)到事件

javascript - Angular : Trying to return JSON data is causing a error in my service?

javascript - 列出 IE8 中的所有 Array.prototype 函数-

javascript - 如何使用 JavaScript 将一个 div 的内容克隆到另一个 div 中?