Sam
Sam

Reputation: 14586

angularjs: passing filtered array to directive

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

I've tried the following:

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

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 ?

EDIT

Here's the full code:

<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>

and the directive:

(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) {                
        }
    };
}
})();

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

EDIT 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; });
        };
    }

and in the view:

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

But that still gives me the same error.

Upvotes: 4

Views: 3340

Answers (1)

dhavalcengg
dhavalcengg

Reputation: 4713

Your both questions are related to each other.

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.

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.

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.

Upvotes: 3

Related Questions