...">

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

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

 (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 selected when the identifier is found in csv. For example, id 5 and 78 is in csv, so these two values ​​must be selected initially

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

+5
source share
3 answers

You can change csv to an array of numbers:

 $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 id index in html

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

You need to use .indexOf inside the 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

+4
source

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

+1
source

All Articles