'ng-repeat'上的自定义过滤器会覆盖范围

时间:2016-07-05 15:38:07

标签: javascript arrays angularjs angularjs-ng-repeat angularjs-filter

我的目标是用另一个数组的教师名称替换一个输出数组的teacher-id(f_teacher)。我写了一个自定义过滤器,应该做的工作:

angular.module('core')
.filter('replaceId', function () {                   //filter, which replaces Id's of one array, with corresponding content of another array
    return function (t_D, s_D, t_prop, s_prop) {     //data of target, data of source, target property, source property
        var replacment = {};
        var output = [];
        angular.forEach(s_D, function (item) {
            replacment[item.id] = item[s_prop];      //replacment - object is filled with 'id' as key and corresponding value
        });
        angular.forEach(t_D, function (item) {
            item[t_prop] = replacment[item[t_prop]]; //ids of target data are replaced with matching value
            output.push(item);
        });
        return output;
    }
});

我像这样使用'ng-repeat':

<tr ng-repeat="class in $ctrl.classes | filter:$ctrl.search | replaceId:$ctrl.teachers:'f_teacher':'prename' | orderBy:sortType:sortReverse">
    <td>{{class.level}}</td>
    <td>{{class.classNR}}</td>
    <td>{{class.f_teacher}}</td>
</tr>

但它只输出一个空列。现在奇怪的是:如果我按照调试器的步骤进行操作,它将首次执行过滤器。但是当它第二次执行时,它会输出一个空列。

我注意到过滤器返回的对象会覆盖$ ctrl.classes - 数组,但通常不应该这样吗?

这是一个plnkr: https://plnkr.co/edit/EiW59gbcLI5XmHCS6dIs?p=preview

为什么会这样?

感谢您的时间:)

1 个答案:

答案 0 :(得分:0)

第一次通过您的过滤器时,代码会使用f_teacher ID并将其替换为教师名称。第二次通过它尝试做同样的事情,除了现在,而不是在f_teacher获得教师ID,它找到教师的名字,所以它不起作用。你可以通过制作类的副本而不是直接修改它来修复它。 e.g。

angular.forEach(t_D, function (item) {
    var itemCopy = angular.copy(item);
    itemCopy[t_prop] = replacment[itemCopy[t_prop]];
    output.push(itemCopy);
});

https://plnkr.co/edit/RDvBGITSAis3da6sWnyi?p=preview

修改

原始解决方案将触发无限摘要,因为过滤器每次运行时都会返回对象的新实例,这将导致角度思考某些内容已更改并重新触发摘要。您是否可以使用getter函数获取教师名称而不是使用过滤器?

$scope.getTeacherName = function(id) {
  var matchingTeachers = $scope.teachers.filter(function(teacher) {
    return teacher.id == id;
  })

  //Should always be exactly 1 match.
  return matchingTeachers[0].prename;
};

然后在HTML中你可以像

一样使用它
<tr ng-repeat="class in classes">
  <td>{{class.level}}</td>
  <td>{{class.classNR}}</td>
  <td>{{getTeacherName(class.f_teacher)}}</td>
</tr>

https://plnkr.co/edit/gtu03gQHlRIMsh9vxr1c?p=preview