angularjs:将过滤后的数组传递给指令 [英] angularjs: passing filtered array to directive

查看:18
本文介绍了angularjs:将过滤后的数组传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将过滤后的数组传递给指令的方法:

I'm looking for a way to pass a filtered array to a directive:

我尝试了以下方法:

<my-directive model="myArray | filter:{myProperty: 'some value' }" /> 

但这不起作用.我认为它应该与 ng-repeat 一起使用,因为这里我只是传递一个函数而不是过滤后的数组.

but that does not work. I think it's meant to be used with ng-repeat, because here I'm just passing a function instead of the filtered array.

有没有办法做到这一点,除了制作我的数组的过滤副本?

Is there a way to do that, other than making a filtered copy of my array ?

编辑

完整代码如下:

<request-service type="editing" jobs="vm.selectedMaterial.jobs | filter:{service.code: 'ED'}"></request-service>
<request-service type="translation" jobs="vm.selectedMaterial.jobs | filter:{service.code: 'TR'}"></request-service>

和指令:

(function () {
'use strict';

var directiveId = 'requestService';

angular.module('comp.domain.directives').directive(directiveId,  [directiveFunc]);

function directiveFunc(dependency) {
    return {
        restrict: 'E',
        templateUrl: 'app/dm/views/templates/requestService.html',
        scope: {
            type: '@',
            jobs: '='
        },
        link: function (scope, element, attrs) {                
        }
    };
}
})();

这样做时,我收到错误将循环结构转换为 JSON"

when doing so, I get the error 'Converting circular structure to JSON'

编辑 2

按照建议的解决方案,我做到了:

Following suggested solution, I did that:

 $scope.filterJob = function (type) {
        if ($scope.vm.selectedMaterial) {
            return $scope.vm.selectedMaterial.jobs.filter(function (job) { return job.service.code === type; });
        };
    }

并在视图中:

  <request-service type="ED" jobs="filterJob('ED')"></request-service>

但这仍然给我同样的错误.

But that still gives me the same error.

推荐答案

你的两个问题相互关联.

Your both questions are related to each other.

您可以在 ng-model 上应用过滤器,但您不应该这样做.因为它会给你在第二个问题中遇到的错误.

You can apply filter on on ng-model, but you should not do that. Because it will give you error you are facing in your second question.

当您将过滤器作业传递给指令时,angular 将监视您的作业变量.因此,当在指令 watch 中分配作业时,将再次触发过滤器,这将一直持续到 angular 达到最大摘要周期.

When you pass filter job to your directive, angular will place a watch on your jobs variable. So when jobs gets assigned in directive watch get called, which will trigger filter again, and this will goes on until maximum digest cycle reached by angular.

为了避免这种情况,您可以创建一个过滤器方法并在 ng-model 中传递该方法.这样您就可以避免副本创建和最大摘要周期错误.

To avoid this situation, you can create a filter method and pass that method in ng-model. This way you can avoid both copy creation and maximum digest cycle error.

这篇关于angularjs:将过滤后的数组传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆