ng-if或ng-checked匹配逗号分隔值

时间:2015-06-09 05:42:27

标签: html arrays angularjs checkbox angular-ng-if

我有以下HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-ngModel-getter-setter-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script src="app.js"></script>

</head>
<body ng-app="getterSetterExample">
<div ng-controller="ExampleController">
<form name="userForm">

<label ng-repeat="id in ids">
    <input type="checkbox" 
           value="{{id.id}}"
           ng-checked="id.id == csv"> {{id.id}}
</label>

</form>
</div>
</body>
</html>

控制器是

(function(angular) {
  'use strict';
 angular.module('getterSetterExample', []).controller('ExampleController', ['$scope', function($scope) {

 $scope.csv = '5,6,76,78';
 $scope.ids = [
    {id:5},
    {id:64},
    {id:456},
    {id:47},
    {id:767},
    {id:78},
    {id:55},
    {id:98}
];

 }]);
})(window.angular);

我希望在csv中找到id后选中复选框。例如,id 5和78在csv中,因此最初应选择这两个值复选框

这是http://plnkr.co/edit/XoW4hARWlzN5iTMuCJW1

3 个答案:

答案 0 :(得分:7)

您可以将csv更改为数字数组:

$scope.csv = [5,6,76,78];
//If you REALLY need it as a string
$scope.csv = '5,6,76,78'.split(',').map(Number);

然后检查html中的id索引

<label ng-repeat="id in ids">
    <input type="checkbox" 
           value="{{id.id}}"
           ng-checked="csv.indexOf(id.id) != -1"> {{id.id}}
</label>

答案 1 :(得分:4)

您需要在.indexOf表达式ng-checked内使用!=

<强>标记

  <label ng-repeat="id in ids">
    <input type="checkbox" 
           value="{{id.id}}"
           ng-checked="csv.indexOf(id.id) != -1"> {{id.id}}
  </label>

<强>代码

$scope.csv = '5,6,76,78'.split(',');

Demo Plunkr

答案 2 :(得分:1)

您需要将csv字符串转换为数组

(function(angular) {
  'use strict';
angular.module('getterSetterExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
     $scope.csv = '5,6,76,78';
     $scope.csv1 = $scope.csv.split(',');
     console.log($scope.csv1);

     $scope.ids = [
        {id:5},
        {id:64},
        {id:456},
        {id:47},
        {id:767},
        {id:78},
        {id:55},
        {id:98}
 ];
    $scope.isInArray = function(value) {
        return $scope.csv1.indexOf(value.toString()) > -1;
    }
 }]);
})(window.angular);

http://plnkr.co/edit/YGkCKZoo3JlB7iGQRDPn?p=preview