我有以下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中,因此最初应选择这两个值复选框
答案 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(',');
答案 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);