【问题标题】:AngularJS chained selectAngularJS 链式选择
【发布时间】:2013-12-09 11:42:19
【问题描述】:
<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/

【问题讨论】:

标签: javascript angularjs loops model linked-list


【解决方案1】:

问题是因为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>

要使代码正常工作,sameId 必须在 fessCntrl 的范围内定义。

$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;
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多