Green Computers
Green Computers

Reputation: 753

How to use ng-if and ng-options together in angular 1

I used below syntax to display username. I want to display username when (user.company==userData.company) in the below list. Please help me to achieve this.

<select ng-options="user.FirstName+' 'user.LastName for user in companyUsers | orderBy:'FirstName' track by user.Id" ng-if="user.company==userData.company" ng-model="selectedUser" ng-change="loadListNew()">
</select>

Upvotes: 2

Views: 12724

Answers (3)

alfishan aqeel
alfishan aqeel

Reputation: 220

    You may move your logic to controller rather than in html. You may filter data $scope.companyUsers before bind it to select options. 

    $scope.companyUsers =  // where you assign the value to companyUsers of scope variable. below this code do something like
    $scope.companyUsers = $scope.companyUsers.map( function(companyUserObj){
     if(companyUserObj.company==$scope.userData.company)
    {
       return companyUserObj;
    }

    })
now bind this $scope.companyUsers to select options as below.
<select ng-options="user.FirstName+' '+user.LastName for user in companyUsers | orderBy:'FirstName' track by user.Id" ng-model="selectedUser" ng-change="loadListNew()">
</select>

Upvotes: 0

Louis Lecocq
Louis Lecocq

Reputation: 1814

Using ng-if="user.company==userData.company" does not work because that would be applied to the select element.

Filters Options

Instead, you can use a filter directly inside your ng-options like in this example.

Filter Document

https://docs.angularjs.org/api/ng/filter/filter

Upvotes: 1

Jeffrey Roosendaal
Jeffrey Roosendaal

Reputation: 7157

There's an error in your code: user.FirstName + ' ' + user.LastName, you forgot the second +.

Updated code:

<select ng-options="user.FirstName + ' ' + user.LastName for user in companyUsers | orderBy:'FirstName' track by user.Id" 
    ng-if="user.company==userData.company"
    ng-model="selectedUser"
    ng-change="loadListNew()">
</select>

But the problem is that ng-if does not work with ng-options, because ng-options does not create a new scope.

What you should do is create a filter, which removes the data from the input, so ng-options will skip it. You can apply it both before or after your orderBy-filter.

Upvotes: 0

Related Questions