带选项的ng-repeat不会将对象作为值返回

时间:2016-12-08 00:15:28

标签: javascript angularjs ng-repeat ng-options

我在

中有一个循环“ng-repeat”
<select ng-model="something"></select>

以便列表中的每个选项都呈现为

<option> 

在select块内。我的目标是使“某事物”(附加到选择的ng模型)等于列表内的选定对象。此时,当我将“value =”{{option}}“作为选项的参数时,我将JSON对象作为String。但我需要的是将对象作为对象。代码如下所示:

<select ng-model="something">
    <option ng-repeat="option in list" value="{{option}}">{{option.name}}</option>
</select>

我想要的东西很容易通过使用ng-options完成,但我需要根据option.anotherField为每个

添加额外的“样式”参数
<option>

2 个答案:

答案 0 :(得分:0)

您可以使用ng-value代替值,它可以为您提供所需的对象:

<select ng-model="something">
    <option ng-repeat="option in list" ng-value="option">{{option.name}}</option>
</select>

答案 1 :(得分:0)

tempsomething)指令的帮助下,通过ng-change代理进行处理及与$scope.setModel变量的关系怎么样:

(function(angular) {
  'use strict';
angular.module('app', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.list = [{name:'Tom',age:23},{name:'Max',age:33},{name:'Sam',age:43}];
    $scope.something = $scope.list[0];
    $scope.temp = $scope.something.name;    

    $scope.setModel = function(){
      for(var item of $scope.list)
        if(item.name == $scope.temp){
          $scope.something = item;
          break;
        }          
    }    
 }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <div ng-app='app' ng-controller="ExampleController">
    <select ng-change='setModel()' ng-model='temp'>
      <option ng-repeat='option in list track by option.name' ng-attr-title='{{option.age}}'>{{option.name}}</option>
    </select>
    <div>something: {{something | json}}</div>
  </div>