AngularJS:用两个JSON数组填充复选框列表,最初检查了一个数组中的一些项

AngularJS: Populating checkbox list with two JSON arrays and initially checked some items from one array

本文关键字:数组 检查 一个 复选框 两个 JSON 列表 AngularJS 填充      更新时间:2023-09-26

在我的AngularJS应用程序中有一个复选框列表。此列表表示用户的某些兴趣。用户可以从列表中选择一个或多个项目。HTML

<html>
   <head>
      <title>User Interests</title>
      <script src="../scripts/angular.min.js"></script>
      <script src="../scripts/userinterests.js"></script>
      <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
      <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
   </head>
   <body>
      <div ng-app="userinterests">
         <form ng-submit="submit()" ng-controller="userinterestsCtrl">
            <div ng-repeat="userinterest in userinterests">
               <input type="checkbox" checkbox-group /> <label>{{userinterest.interestKey}}</label>
            </div>
            <input type="submit" id="submit" value="Submit" />
         </form>
      </div>
   </body>
</html>

在我的javascript文件中,我首先从后台函数获得一个列表,这个列表包含所有兴趣。如果这个后端调用成功,那么我调用另一个函数来从该用户获取已经选择的项目,这将返回另一个列表,其中包含用户已经选择的兴趣。现在我有两个列表(所有兴趣的列表和用户已经选择的兴趣的列表)。现在我想显示一个包含所有兴趣的复选框列表,但我想检查客户已经选择的项目。

这是我的javascript,看起来像

var app = angular.module('userinterests', []);
app.controller('userinterestsCtrl', function($scope, $http) {
// Get full interests list
$http({
    method : 'POST',
    url : './test/userInterests',
    headers : {
        'Content-Type' : 'application/json'
    }
}).success(function(response) {
    console.log('response=>' + response);
    $scope.interests_array = [];
    $scope.userinterests = response;
    console.log($scope.userinterests);
    // Get already selected interests
    $http({
        method : 'POST',
        url : './test/savedInterests',
        headers : {
            'Content-Type' : 'application/json'
        },
        params : {
            user_email : localStorage.getItem("user_email")
        }
    }).success(function(response) {
        console.log('response=>' + response);
        $scope.savedinterests = response;
        console.log(response);
    }).error(function(response, status, headers, config) {
        console.log('failure');
    });
}).error(function(response, status, headers, config) {
    console.log("failure");
});
$scope.submit = function() {
    console.log('Submiting...');
    console.log($scope.interests_array.join(", "));
    var user_email = localStorage.getItem("user_email");
    var preferences = "[" + $scope.interests_array.join(", ") + "]";
    console.log('preferences=>' + preferences);
    $http({
        method : 'POST',
        url : './test/setUserInterests',
        headers : {
            'Content-Type' : 'application/json'
        },
        params : {
            user_email : user_email,
            preferences : preferences
        }
    }).success(function(response) {
        console.log('response=>' + response);
    }).error(function(response, status, headers, config) {
        console.log('failure');
    });
};
}).directive(
    "checkboxGroup",
    function() {
        return {
            restrict : "A",
            link : function(scope, elem, attrs) {
                // Determine initial checked boxes
                if (scope.interests_array.indexOf(scope.userinterest.interestKey) !== -1) {
                    elem[0].checked = true;
                }                   
                // Update array on click
                elem.bind('click', function() {
                    var index = scope.interests_array.indexOf(scope.userinterest.interestKey);
                    // Add if checked
                    if (elem[0].checked) {
                        if (index === -1)
                            scope.interests_array.push(scope.userinterest.interestKey);
                    }
                    // Remove if unchecked
                    else {
                        if (index !== -1)
                            scope.interests_array.splice(index, 1);
                    }
                    // Sort and update DOM display
                    // scope.$apply(scope.array.sort(function(a, b) {
                    // return a - b
                    // }));
                });
            }
        }
    });

样本数据

        $scope.userinterests = [{
        "key": "test1",
        "score": 1.0
      }, {
        "key": "test2",
        "score": 1.0
      }, {
        "key": "test3",
        "score": 1.0
      }, {
        "key": "test4",
        "score": 1.0
      }, {
        "key": "test5",
        "score": 1.0
      }, {
        "key": "test6",
        "score": 1.0
      }, {
        "key": "test7",
        "score": 1.0
      }, {
        "key": "test8",
        "score": 1.0
      }, {
        "key": "test9",
        "score": 1.0
      }, {
        "key": "test10",
        "score": 1.0
      }, {
        "key": "test11",
        "score": 1.0
      }];
      var selectedInterests = [{
        "key": "test1",
        "score": 1.0
      }, {
        "key": "test2",
        "score": 1.0
      }, {
        "key": "test3",
        "score": 1.0
      }];

如果有人能帮助我实现这一目标,我将不胜感激。

谢谢

您只需在运行时在userInterests数组中创建一个额外的selected属性即可。

userInterests.forEach(function(item){
   savedInterests.forEach(function(savedItem){
      if(savedItem.interestKey === item.interestKey){
         item.selected = true;
      }
   })
})

然后在你的模板中只需使用

<div ng-app="userinterests">
         <form ng-submit="submit()" ng-controller="userinterestsCtrl">
            <div ng-repeat="userinterest in userinterests">
               <input type="checkbox" checkbox-group ng-model="userinterest.selected" /> <label{{userinterest.interestKey}}</label>
            </div>
            <input type="submit" id="submit" value="Submit" />
         </form>
      </div>

希望能有所帮助。

检查此项。其简单易用的

var app = angular.module('userinterests', []);
app.controller('userinterestsCtrl', function($scope, $http) {
  $scope.userinterests = [{
"key": "test1",
"score": 1.0
  }, {
"key": "test2",
"score": 1.0
  }, {
"key": "test3",
"score": 1.0
  }, {
"key": "test4",
"score": 1.0
  }, {
"key": "test5",
"score": 1.0
  }, {
"key": "test6",
"score": 1.0
  }, {
"key": "test7",
"score": 1.0
  }, {
"key": "test8",
"score": 1.0
  }, {
"key": "test9",
"score": 1.0
  }, {
"key": "test10",
"score": 1.0
  }, {
"key": "test11",
"score": 1.0
  }];
  var selectedInterests = [{
"key": "test1",
"score": 1.0
  }, {
"key": "test2",
"score": 1.0
  }, {
"key": "test3",
"score": 1.0
  }];
  for (var i = 0; i < $scope.userinterests.length; i++) {
    if (JSON.stringify(selectedInterests).indexOf(JSON.stringify($scope.userinterests[i])) > 0) {
      $scope.userinterests[i]['active'] = true;
    } 
  }
});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<div ng-app="userinterests">
  <form ng-submit="submit()" ng-controller="userinterestsCtrl">
    <div ng-repeat="userinterest in userinterests">
      <input type="checkbox" ng-model='userinterest.active'/>
      <label>{{userinterest.key}}</label>
    </div>
    <input type="submit" id="submit" value="Submit" />
    <pre>{{selectedInterests | json}}</pre>
  </form>
</div>

使用$filter进行搜索,然后在user_interest数组中添加一个键,并根据该键选择/取消选择复选框。

$scope.userinterests = [{
"key": "test1",
"score": 1.0
}, {
"key": "test2",
"score": 1.0
}, {
"key": "test3",
"score": 1.0
}, {
"key": "test4",
"score": 1.0
}, {
"key": "test5",
"score": 1.0
}, {
"key": "test6",
"score": 1.0
}, {
"key": "test7",
"score": 1.0
}, {
"key": "test8",
"score": 1.0
}, {
"key": "test9",
"score": 1.0
}, {
"key": "test10",
"score": 1.0
}, {
"key": "test11",
"score": 1.0
}];
var selectedInterests = [{
"key": "test1",
"score": 1.0
}, {
"key": "test2",
"score": 1.0
}, {
"key": "test3",
"score": 1.0
}];
user_interests.map(function(c,i){
  var found = $filter('filter')(saved_interests, {key: c.key}, true);
  if (found.length) {
      c.active = 1;
      user_interests[i] = c;
  }
});

我只使用一个视图模型对象,它有一个额外的"selected"属性,并使用ng模型将复选框绑定到此属性。

因此,基本上你会创建一个新的对象,看起来像是对用户兴趣的响应,但每个兴趣都有一个"selected"布尔属性。可以使用Array.map创建此新阵列。

然后,您可以使用ngRepeat迭代新数组,为每个条目创建一个复选框,该复选框绑定到"selected"属性。

在向服务器写入时,可以使用Array.filter生成一个仅包含选定项的新数组,如您提到的savedinterest的响应。