Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-if or ng-checked matching from comma separated value

I have following 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>

And the controller is

(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);

I want the checkbox checked when id found in csv. For example id 5 and 78 is in csv so these two values checkbox should be selected initially

Here it is http://plnkr.co/edit/XoW4hARWlzN5iTMuCJW1

like image 610
Muzafar Khan Avatar asked Jun 09 '15 05:06

Muzafar Khan


1 Answers

You can change the csv to an array of number:

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

Then check the index of id in the html

<label ng-repeat="id in ids">
    <input type="checkbox" 
           value="{{id.id}}"
           ng-checked="csv.indexOf(id.id) != -1"> {{id.id}}
</label>
like image 198
Huy Hoang Pham Avatar answered Nov 12 '22 18:11

Huy Hoang Pham