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

3k views Asked by At

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

3

There are 3 answers

1
Huy Hoang Pham On BEST ANSWER

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>
6
Pankaj Parkar On

You need to use .indexOf inside ng-checked expression with !=.

Markup

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

Code

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

Demo Plunkr

1
Debasish Mohapatra On

You need to convert the csv string to an array,

(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