AngularJS ng-options从与另一个范围var匹配的数组中获取选定选项

时间:2015-12-10 01:03:15

标签: angularjs ng-options default-selected

我有一个数组和一个var

$scope.fcFeedTypes = [{"name":"Plain Text","value":"Plain Text"},{"name":"MQ Message","value":"MQ Message"}];
}
$scope.feedEditor.ft = "MQ Message"; // this is dynamically obtained from some other source

我想要一个基于$scope.feedEditor.ft

值的默认选择的下拉列表选择

HTML:

<select ng-model="fcFeedTypes"
        ng-options="ft.name for ft in fcFeedTypes"
        ng-init="ft=feedEditor.ft">

我是AngularJS的新手,需要一些帮助...

1 个答案:

答案 0 :(得分:1)

If you just want the string "MQ Message" (or the value of whatever a user selects) as your ng-model value, then it's quite simple:

<select ng-model="someModelName"
    ng-options="ft.value as ft.name for ft in fcFeedTypes"
    ng-init="someModelName=feedEditor.ft">

If you want the full object as the ng-model value, then you've got to find the right one in JS. It must be referentially/strictly equal to the one in the options.

<select ng-model="someModelName"
    ng-options="ft.name for ft in fcFeedTypes">

-

$scope.fcFeedTypes = [{"name":"Plain Text","value":"Plain Text"},{"name":"MQ Message","value":"MQ Message"}];

$scope.feedEditor.ft = "MQ Message"; // this is dynamically obtained from some other source

angular.forEach($scope.fcFeedTypes, function(feedType){
  if(feedType.value === $scope.feedEditor.ft){
    $scope.someModelName = feedType;
  }
});