Thursday, 8 January 2015

Binding select tag with ng-options in AngularJS..


angularjs
When I am onto creating a combo list using select tag first I thought of using ng-repeat then I thought let me try something more useful so that I can reduce my code and make it more effective and readable. So I worked out with ng-options which helped me to populate my list with a single line of code. So here is the code where I have commented the <option></option> section which actually containing the ng-repeat.



<!DOCTYPE html><html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
      angular.module('myApp',[])
        .controller('AngController',function($scope) {
          $scope.dataSet = [
          {Name:'Larry',Company:'Google'},
          {Name:'Mark',Company:'Facebook'},
          {Name:'Steve',Company:'Apple'},
          {Name:'Bill',Company:'Microsoft'},
          {Name:'Michael',Company:'Dell'},
          {Name:'Ellison',Company:'Oracle'}
          ];
          $scope.myData = $scope.dataSet[0];
        });
    </script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="AngController">
    <select ng-model="myData" ng-options="data.Name for data in dataSet" ng-change="getCompany"></select> - {{myData.Company}}
    <!--    <select ng-model="myData">
        <option ng-repeat="data in dataSet">{{data}}</option>
      </select> -->
    </div>
  </body>
</html>

 
Here is the demo output..


- {{myData.Company}}

No comments: