简体   繁体   English

预选选项表格ng-options list

[英]Pre-select option form ng-options list

I'm trying to preselect a item in the list which is generated by ng-options directive. 我试图在ng-options指令生成的列表中预先选择一个项目。 Could someone please tell me whats happening in the plunker? 有人可以告诉我the子发生了什么吗?

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

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
  <script>
    function MyCntrl($scope) {
      $scope.prop = {
        "type": "select",
        "name": "Service",
        "values": [{
          'name': "Service 1"
        }, {
          'name': "Service 2"
        }, {
          'name': "Service 3"
        }, {
          'name': "Service 4"
        }]
      };
      $scope.selected1 = $scope.prop.values[1]
      $scope.selected2 = {
        "name": "Service 2"
      }

    }
  </script>
</head>

<body>

  <div ng-controller="MyCntrl">
    Works <br>
  <select ng-model="selected1" ng-options="v.name for v in prop.values">
    </select> {{selected1}} <br>
    Does not work. Why? <br>
    <select ng-model="selected2" ng-options="v.name  for v in prop.values">
    </select>
    {{selected2}}
  </div>
</body>
</html>

Bijay Rai's statement is correct but not full answer. Bijay Rai的说法是正确的,但不是完整答案。

ngOption has rather complicated expressions and you should bother to examine documentation . ngOption表达式相当复杂,您应该检查文档 If you change the way the option's object is being tracked you can avoid using same object by reference as stated. 如果更改了跟踪选项对象的方式,则可以避免通过引用使用same object For example, use select as pattern 例如,使用select as模式

<select ng-model="selected2" ng-options="v.id as v.name for v in prop.values">
</select>

Then you can simply assign selected like this: 然后,您可以像这样简单地分配所选内容:

  $scope.selected2 = 3;

Updated plunkr 更新的plunkr

$scope.prop = {
        "type": "select",
        "name": "Service",
        "values": [{
          'name': "Service 1"
        }, {
          'name': "Service 2"
        }, {
          'name': "Service 3"
        }, {
          'name': "Service 4"
        }]
      };

ng-options getting data from prop.values .... so selected1 is working cause it is predefined as $scope.prop.values[1] ng-optionsprop.values中获取数据..所以selected1起作用了,因为它已预定义为$ scope.prop.values [1]

whereas selected2 is not referring to data inside prop.values ..... selected2并不引用prop.values内部的数据..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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