Reputation: 195
I have an array as follows:
$scope.age = 2;
$scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}]
I want the ng-options
to be dynamic i.e.,
If the age is 2 then show all objects of people in ng-options.
If the age is 1 then show object with name as "Sam".
$scope.age
can have value either 1 or 2.
How can I do this in AngularJS without writing different block of select statements?
Upvotes: 2
Views: 3369
Reputation: 12022
You can use AngularJS filter as below with a custom function.
Working sample: (type 1 or 2 in the textbox below to test this)
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>
Upvotes: 0
Reputation: 13997
The ng-options
directive can also parse filters, so you can do something like this:
<select ng-options="person as person for person in people | filter:{age:age}">
</select>
See this jsfiddle
Upvotes: 0
Reputation: 8324
You could bind the select to the result of a function:
<select ng-options="person as person for person in getPersons()">
</select>
Then setup your scope like this:
$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;
};
Upvotes: 1