Skip to content Skip to sidebar Skip to footer

Select Default Option In A Dropdown, Save The Value In The Value Attribute Of The Dropdown. Angular.js. Angular.js

I have seen infinity of post to try to choose by default an option in a dropdown. But I have not been able to achieve it. I have an array of some countries. $scope.regions = [

Solution 1:

Working demo: http://plnkr.co/edit/zhye91pDUEMgaZnXZGWE?p=preview

You basically create a default region by doing

$scope.select = $scope.selectThisId.id;
$scope.regionSelected = {};

then create a select tag with ng-options, binding it to the model, and calling ng-init on the model.

<select ng-options="item as item.name for item in regions track by item.code" 
        ng-model="regionSelected" ng-init="regionSelected.code = select">
</select>

Solution 2:

You can add a filter to your controller to get the default region (don't forget to add $filter after $scope):

$scope.defaultValue = $filter('filter')($scope.regions, {code: $scope.selectThisId.id}, true)[0];

and then add this to your select in your view

ng-init="select = defaultValue"

Demo

Solution 3:

DEMO

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.regions = 
 [
      {
        name: "COLOMBIA",
        code: 5
      },
      {
        name: "ARGENTINA",
        code: 6
      },
      {
        name: "BRAZIL",
        code: 7
      }
  ];
  
  $scope.selectThisId={
    "id":6,
    "animal":'dog',
    "variable":'xxx32'
 };
 
 $scope.region=$scope.selectThisId.id;
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myapp"><fieldsetng-controller="FirstCtrl"><selectng-options="item.code as item.name for item in regions"ng-model="region"></select></fieldset></div>

Post a Comment for "Select Default Option In A Dropdown, Save The Value In The Value Attribute Of The Dropdown. Angular.js. Angular.js"