Search code examples
javascriptangularjsselectng-options

Making ng-options dynamic in AngularJS


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?


Solution

  • 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;
    };