在AngularJS中使ng-options动态化

时间:2016-12-20 09:31:13

标签: javascript angularjs select ng-options

我有一个数组如下:

$scope.age = 2;
$scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}]

我希望ng-options是动态的,即 如果年龄为2,则在ng-options中显示所有人的对象。 如果年龄为1,则显示名称为“Sam”的对象。

$scope.age的值可以是1或2。

如何在不编写不同的select语句块的情况下在AngularJS中执行此操作?

3 个答案:

答案 0 :(得分:0)

ng-options指令也可以解析filters,所以你可以这样做:

<select ng-options="person as person for person in people | filter:{age:age}">
</select>

请参阅this jsfiddle

答案 1 :(得分:0)

您可以将select绑定到函数的结果:

<select ng-options="person as person for person in getPersons()">
</select>

然后像这样设置范围:

$scope.age = 2;
$scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}]
$scope.getPersons = function() {
    if ($scope.age = 1)
        return $scope.people.filter(function(item) {
            item.name == "Sam";
        });
    else
        return $scope.people;
};

答案 2 :(得分:0)

您可以使用自定义函数的AngularJS filter

工作示例 :( 在下面的文本框中键入1或2以测试此

var app = angular.module('app', []);

app.controller('TestController', function($scope) {
  $scope.age = 2;
  $scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}];
  $scope.filterPeople = function(person) {
     return $scope.age === 2 || person.name === "Sam";
  };
});

angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="TestController">
  Age: <input type="text" ng-model="age" />
  <select ng-options="person as person.name for person in people | filter:filterPeople" ng-model="selected">
  </select>
</div>