Select default option in a dropdown, save the value in the value attribute of the dropdown. Angular.js. Angular.js

前端 未结 3 1337
醉酒成梦
醉酒成梦 2021-01-26 16:31

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.

$sco         


        
相关标签:
3条回答
  • 2021-01-26 16:57

    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>
    
    0 讨论(0)
  • 2021-01-26 17:00

    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

    0 讨论(0)
  • 2021-01-26 17:06

    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>

    0 讨论(0)
提交回复
热议问题