Multi select listbox with dynamid ng-selected values

Multi select listbox with dynamid ng-selected values

 Example: we have two arrays: categories array is a list of categories and selectedcategories is a list selected categories by id. We want to use <select > to display all categories via multi selected categories which matching selectedcategories array values.

Output sample:


Here is full code 



 <!DOCTYPE html>  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head>  
   <title></title>  
   <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>  
   <script src="http://code.angularjs.org/1.2.16/angular.js"></script>  
   <script src="http://code.angularjs.org/1.2.16/angular-resource.js"></script>  
   <script>  
   myWebApp = angular.module('myWebApp', []);  
   myWebApp.controller("Controller01", function ($scope) {  
     $scope.message1 = 'Welcome to UI-Tutorials blog';  
     $scope.categories = [{ "category_id": "1", "category_name": "sports" }, { "category_id": "2", "category_name": "casual" }, {  
       "category_id"  
     : "3", "category_name": "formal"  
     }, { "category_id": "4", "category_name": "party wear" }, {  
       "category_id": "5", "category_name"  
       : "winter"  
     }, { "category_id": "9", "category_name": "summer" }]  
     $scope.selectedcategories = [{ "id": "3" }, { "id": "4" }, { "id": "5" }]  
     $scope.$watch('selectedcategories ', function (nowSelected) {  
       $scope.selectedValues = [];  
       if (!nowSelected) {  
         return;  
       }  
       angular.forEach(nowSelected, function (val) {  
         $scope.selectedValues.push(val.id.toString());  
       });  
     });  
   });  
   </script>   
 </head>  
 <body ng-app="myWebApp">  
   <div ng-controller="Controller01">  
     <select multiple ng-model="selectedValues" style="width: 50%;" size="7">  
       <option ng-repeat="category in categories" value="{{category.category_id}}" ng-selected="{{selectedValues.indexOf(category.category_id.toString())!=-1}}">{{category.category_name}}</option>  
     </select>  
     <h3>You have selected: {{selectedValues}}</h3>  
   </div>  
 </body>   
 </html>  

Demo  at Plunker 
Thanks for you time reading.


No comments:

Post a Comment

Popular Posts