Angular:ngOptions不显示选定的ng-model值

时间:2017-07-01 18:30:23

标签: angularjs

我似乎无法弄清楚为什么ng-optionsng-model<select>内无法正常工作:选定的值name isn&#39;正在显示,但code对象中的element是正确的......

以下是我的目标:

$scope.hierarchyWorkElements = [];
$scope.worksToBeExecuted = [
 {
  id: 1,
  name: "Create Address Point"
 },
 {
  id: 2,
  name: "Create Segment"
 }
];

来自$scope.hierarchyWorkElements数组的一个对象示例:

$$hashKey: "07H",
code: "0",
id: "element1",
name: ""

这是HTML

<div data-ng-repeat="element in hierarchyWorkElements" class="row top-buffer">
  <div class="col-sm-10">
    <select class="form-control"
       ng-model="element.code"
       ng-options="item.id as item.name for item in worksToBeExecuted"></select>
  </div>
</div

提前致谢,亲切的问候!

2 个答案:

答案 0 :(得分:1)

ng-model未按预期工作的原因是element.code是一个字符串,其中item.id是一个整数。您可以更改JSON对象或尝试以下代码。

&#13;
&#13;
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
    $scope.worksToBeExecuted = [{
        id: 1,
        name: "Create Address Point"
    }, {
        id: 2,
        name: "Create Segment"
    }];
    $scope.hierarchyWorkElements = [{
        $$hashKey: "07H",
        code: "1",
        id: "element1",
        name: ""
    }, {
        $$hashKey: "09H",
        code: "2",
        id: "element2",
        name: ""
    }];
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<htmL>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<div data-ng-repeat="element in hierarchyWorkElements" class="row top-buffer">
    <select class="form-control"
       ng-model="element.code"
       ng-options="item.id.toString() as item.name for item in worksToBeExecuted"></select>
</div>
</div>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您在层次结构工作元素内部的对象数组中使用ng-model作为代码属性。这是worksToBeExecuted中作为id属性的值。这里的类型不同,一个是字符串&amp;其他应该修复的数字。然后你可以通过$ index跟踪ng-repeat&amp;实际上使用$ scope.hierarchyWorkElements [index] .code查看所有选择元素的模型值 此外,我在这里假设hierarchyWorkElements数组是;

$scope.hierarchyWorkElements=[{
                                code: "0",
                                id: "element1",
                                name: ""
                              },
                              {
                                code: "1",
                                id: "element2",
                                name: ""
                              }];

the docs

这是模拟您的要求的示例,显示初始&amp;更改模型值后,查看选择下拉列表的值。