[英]ng-if or ng-checked matching from comma separated value
我有以下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中,因此最初应选择这两个值复选框
您可以将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>
你需要在ng-checked
表达式中使用.indexOf
!=
。
标记
<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(',');
您需要将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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.