在其他变量中包含的下拉列表中选择默认选项

时间:2017-04-29 17:49:39

标签: javascript angularjs

我看到无限的帖子试图在下拉菜单中默认选择一个选项。但我无法实现它。我有一些国家。

$scope.regions = 
 [
  {
    name: "COLOMBIA",
    id: 5
  },
  {
    name: "ARGENTINA",
    id: 6
  },
  {
    name: "BRAZIL",
    id: 7
  }
 ];

我有这个变量:

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

我需要下拉值等于

的id属性
$scope.region=$scope.selectThisId.id;

可变

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

2 个答案:

答案 0 :(得分:0)

您必须将id更改为代码,并且$ scope.region必须等于$ scope.selectThisId。

Follow the code

angular.module('angularApp', [])
  .controller('controller', function($scope) {
    $scope.regions = [{
      name: "COLOMBIA",
      code: 5
    }, {
      name: "ARGENTINA",
      code: 6
    }, {
      name: "BRAZIL",
      code: 7
    }];

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

    // selected value by default is 'argentina'
    //$scope.select = $scope.regions[1];
    $scope.select = $scope.selectThisId; // the object here
  })

答案 1 :(得分:0)

您可以在控制器中添加过滤器以获取默认区域(不要忘记在$filter之后添加$scope):

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

然后将其添加到您视图中的选择

ng-init="select = defaultValue"

Demo