Search code examples
javascriptangularjsangularjs-scopeng-options

Select dropdown as selected using value in ng-options AngularJS


I am trying to set China as selected country but somehow it is only setting China in dropdown if I am doing like - $scope.countrySelected = $scope.countryList[5];

Let me know if it is possible to set value by text only as through Service I am getting China as a text only which I need to match.

HTML Code -

<select 
 ng-options="country.c_name for country in countryList track by country.c_id" 
 ng-model="countrySelected">
</select>

SCRIPT CODE -

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function($scope){
  $scope.countryList = [
    {c_id: 1, c_name: 'Iran'},
    {c_id: 2, c_name: 'Iraq'},
    {c_id: 3, c_name: 'Pakistan'},
    {c_id: 4, c_name: 'Somalia'},
    {c_id: 5, c_name: 'Libya'},
    {c_id: 6, c_name: 'China'},
    {c_id: 7, c_name: 'Palestine'}
  ];

  $scope.countrySelected = 'China';
})

Working Plnkr - http://plnkr.co/edit/6qSvuuOtJHVSoNWah0KR?p=preview


Solution

  • You can use filter method which accepts as parameter a callback function.

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    $scope.countrySelected = $scope.countryList.filter(function(item){
         return item.c_name=='China';
    })[0];
    

    Working Plnkr

    Also, another method is to use find method.

    $scope.countrySelected = $scope.countryList.find(function(item){
         return item.c_name=='China';
    });
    

    For older version of browser which are incompatible with these methods you can implement your own filter method.

    Array.prototype.filter = function(func, thisArg) {
       'use strict';
       if ( ! ((typeof func === 'Function') && this) )
          throw new TypeError();
    
       var len = this.length >>> 0,
       res = new Array(len), // preallocate array
       c = 0, i = -1;
       if (thisArg === undefined)
          while (++i !== len)
            // checks to see if the key was set
            if (i in this)
               if (func(t[i], i, t))
                 res[c++] = t[i];
       else
          while (++i !== len)
             // checks to see if the key was set
             if (i in this)
                if (func.call(thisArg, t[i], i, t))
                  res[c++] = t[i];
       res.length = c; // shrink down array to proper size
       return res;
    };
    

    Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter