提供相同数据的不同绑定

时间:2015-05-20 12:38:55

标签: javascript angularjs data-binding

使用AngularJS,假设数组decodeURIComponent具有以下结构的项目:

$scope.data.children

是否有一种简单的方法可以引用所有{ "sku" : "<sku>", "selected" : "<boolean>" } 个孩子,理想情况下会在selected = true中表示?

所以,例如,如果

$scope.data.components

然后

$scope.data.children = [
    {"sku" : "A","selected" : "true"},
    {"sku" : "B","selected" : "false"},
    {"sku" : "C","selected" : "true"},
    {"sku" : "D","selected" : "false"}
]

如果$scope.data.components = [ {"sku" : "A","selected" : "true"}, {"sku" : "C","selected" : "true"}, ] 更新为$scope.data.children

然后[{"sku" : "D","selected" : "true"}]

$scope.data.components =

2 个答案:

答案 0 :(得分:0)

$scope.$watch("data.children", setSelected);

var setSelected = function () {
    var selected = []

    for (var i = 0; i < $scope.data.children; i++) {
        if ($scope.data.children[i].selected == "true") {
            selected.push($scope.data.children[i];
        }
    }

    $scope.data.components = selected;
}

答案 1 :(得分:0)

尝试在项目中使用underscore.js。 它让你的生活更容易500%!

并且您的item.selected值存储为字符串,而不是布尔值。

y

http://underscorejs.org/#filter