来自控制器的ng-options和数组

时间:2016-07-27 10:23:49

标签: angularjs

我想在下拉菜单中显示来自控制器的列表。该数组是控制器变量,定义如下:

(function(angular) {
  'use strict';
angular.module('staticSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    self = this;
     self.options = [
        {id: 1, label: "Item 1"},
        {id: 2, label: "Item 2"},
        {id: 3, label: "Item 3"}
      ];

    $scope.data = {
     singleSelect: null,
     multipleSelect: [],
     option1: 'option-1',
    };

    $scope.forceUnknownOption = function() {
      $scope.data.singleSelect = 'nonsense';
    };
 }]);
})(window.angular);

现在,我想在下拉列表中显示此选项数组。脚本如下:

<body ng-app="staticSelect">
  <div ng-controller="ExampleController as ctrl">
    <form name="myForm">
      <label for="singleSelect"> Single select: </label><br>
      <select name="singleSelect" ng-model="data.singleSelect"
        ng-options="ctrl.option.id as ctrl.option.label for ctrl.option in ctrl.options">
      </select><br>
      <tt>selected = {{data.singleSelect}}</tt><br/>
    </form>
  </div>
</body>

如果选项数组在$scope中,那么这样可以正常工作。我是AngularJS的新手。在使用控制器变量时,我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

以下是ng-options属性的外观:

ng-options="option.id as option.label for option in ctrl.options"