2

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?

2
  • What is the logic of 'if age is 2, return Pam and Ham, else if age is 1, return Sam' Commented Dec 20, 2016 at 9:42
  • You can check my answer below Commented Dec 20, 2016 at 10:01

3 Answers 3

1

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;
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

How can this work, please see the conditions and what objects I need to display in ng-options
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.