AngularJS chained select

AngularJS chained select

本文关键字:select chained AngularJS      更新时间:2024-05-06
<select multiple ng-model="comp" ng-options="c.name for c in companies | unique: 'company'" style="width: 100%; height: 200px; float: left; margin-bottom: 20px"></select>
<table>
  <tr ng-repeat="c in comp">
    <td>{{ c.id }}</td>
  </tr>
</table>
<select multiple ng-model="dep" ng-options="c.name for c in departments | filter: {company_id: comp.id}" style="width: 100%; height: 200px; float: left; margin-bottom: 20px"></select>
<select multiple ng-model="pos" ng-options="c.name for c in positions | unique: 'position' | filter: {department_id: dep.id}" style="width: 100%; height: 200px; float: left"></select>

是我的代码的样子,但它只能部分工作。如果我通过ng-repeat循环播放,当我在选择框中单击公司时,c.id打印正常。问题是 - 它不会在我想过滤结果的其他选择框中打印出来。可能是什么原因呢?

JSFiddle: http://jsfiddle.net/9Ymvt/853/

问题是由以下事实引起的:comp是(选定的(公司列表,而不是单个公司。虽然表工作正常(ng-repeat 遍历表(,但过滤器失败,因为comp.id的计算结果为 undefined

这可以通过将我们的过滤器更改为如下来解决:

<div ng-controller="fessCntrl">
    <select multiple ng-model="comp" ng-options="c.name for c in companies | unique: 'company'" style="width: 100%; height: 200px; float: left; margin-bottom: 20px"></select>
    <table>
        <tr ng-repeat="c in comp">
            <td>{{ c.id }}</td>
        </tr>
    </table>
    <pre>{{ comp }}</pre>
    <select multiple ng-model="dep" ng-options="c.name for c in departments | filter:sameId(comp, 'company_id')" style="width: 100%; height: 200px; float: left; margin-bottom: 20px"></select>
    <select multiple ng-model="pos" 
        ng-options="c.name for c in positions | unique: 'position' | filter:sameId(dep, 'department_id')"                
        style="width: 100%; height: 200px; float: left"></select>
</div>

为了使代码正常工作,必须在fessCntrl范围内定义sameId

$scope.sameId = function(grouping, object_id_field_name) {
    return function(object) {
        var obj_id = object[object_id_field_name];
        for (var i = 0; i < grouping.length; i++) {
            if (grouping[i].id == obj_id)
                return true;
        }
        return false;
    }
};