如何在角度1中一起使用ng-if和ng-options

时间:2017-06-30 09:04:31

标签: angularjs ng-options

我使用以下语法显示用户名。我想在下面的列表中显示(user.company==userData.company)时的用户名。请帮助我实现这一目标。

<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>

3 个答案:

答案 0 :(得分:0)

您的代码中出现错误:user.FirstName + ' ' + user.LastName,您忘记了第二个+

更新的代码:

<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>

但问题是ng-if无法与ng-options一起使用,因为ng-options不会创建新范围。

你应该做的是创建一个过滤器,它会从输入中删除数据,因此ng-options会跳过它。您可以在orderBy - 过滤器之前或之后应用它。

答案 1 :(得分:0)

使用ng-if="user.company==userData.company"不起作用,因为它将应用于select元素。

过滤选项

相反,您可以直接在ng-options内使用过滤器,例如example.

过滤文件

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

答案 2 :(得分:0)

    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>