如何在ng-options中使用范围函数

时间:2014-06-10 18:22:52

标签: javascript angularjs

我有两个下降 下拉1

<select data-ng-model="item.company" ng-options="c.id as c.name for a in companylist>
  </select>

在下拉列表1中选择公司值将触发下拉列表2以填充所选公司的员工

下拉2

<select data-ng-model="item.employeeid" ng-options="e.id as e.name for e in getEmployee(item.company)"></select>


 function getEmployee(id) {
            for (var i = 0; i < $scope.companylist.length; i++) {
                if ($scope.companylist[i].id == id) {
                    return $scope.companylist[i].employees;                   
                }
            }
        };

有可能吗?

2 个答案:

答案 0 :(得分:0)

我认为这不会奏效(但我不确定);更好的方法是在第一次下拉更改时使用ng-change并设置一个范围变量,该变量与第二个下拉列表绑定。

下拉1 -

<select data-ng-model="item.company" ng-change="updateEmployee(item.id)" ng-options="c.id as c.name for a in companylist>

下拉2 -

<select data-ng-model="item.employeeid" ng-options="e.id as e.name for e in employees"></select>

代码背后:

function updateEmployee(id) {
   for (var i = 0; i < $scope.companylist.length; i++) {
       if ($scope.companylist[i].id == id) {
          $scope.employees = $scope.companylist[i].employees;                   
       }
   }
};

答案 1 :(得分:0)

我是这样做的..并且有效!!

在dropdown2中

<select data-ng-model="item.employeeid" >
<option ng-repeat="e in getEmployee(item.company)"
          value="{{e.id}}"
          title="{{e.name}}"
          ng-selected="e.id == item.employeeid">{{e.name}}                                                </option>
</select>

使用Javascript:

function getEmployee(id) {
            for (var i = 0; i < $scope.companylist.length; i++) {
                if ($scope.companylist[i].id == id) {
                    return $scope.companylist[i].employees;                   
                }
            }
        };