简体   繁体   中英

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 = 
 [
      {
        name: "COLOMBIA",
        code: 5
      },
      {
        name: "ARGENTINA",
        code: 6
      },
      {
        name: "BRAZIL",
        code: 7
      }
  ];

I have this variable:

$scope.selectThisId={
    "id":6,
    "animal":'dog',
    "variable":'xxx32'
 };

I need the dropdown value to be equal to the id attribute of the

$scope.region=$scope.selectThisId.id;

variable.

http://plnkr.co/edit/nmc8iLz6BIFac0Swfth8?p=preview

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>

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

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; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp"> <fieldset ng-controller="FirstCtrl"> <select ng-options="item.code as item.name for item in regions" ng-model="region"></select> </fieldset> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM