0

I'm trying to use a custom directive on an element with ng-repeat, like so:

<article ng-repeat="product in ctrl.products" class="product entity" 
    product="product" selected-retailer="ctrl.selectedRetailer"></article>

I've read that, in order for this to work, you need to set the priority on your custom directive to something higher than the ng-repeat directive. So I've defined my directive like so, setting the priority to 1001:

angular.module('MainApp')
    .directive('product', function () {
        return {
            restrict: 'A',
            scope: {
                product: '=',
                selectedRetailer: '='
            },
            priority: 1001,
            templateUrl: '/Static/Templates/product.html',
            link: function ($scope, $element, $attributes) {
                $element.addClass('testCssClass');
            }
        };
    });

...and this works, it loops through my products.

The problem is, I'm also trying to set a CSS class on the directive's element (article) using:

$element.addClass('testCssClass');

...in the link function, but it doesn't seem to work.

But if I remove ng-repeat and just show first product item, like so:

<article class="product entity" product="ctrl.products[0]"
    selected-retailer="ctrl.selectedRetailer"></article>

...the CSS class shows up just fine (i.e. "product entity testCssClass").

How can I get this to work with ng-repeat?

1 Answer 1

1

This was indeed a very unpleasant surprise form Angular.

You have to set priority to -1001 for it to work. Reason: (from the docs of priority in the $compile service)

Priority

[...] Directives with greater numerical priority are compiled first. [...] post-link functions are run in reverse order

From a small investigation (fiddle) it seems that the $element passed to the link function is the HTML comment helper inserted by ng-repeat.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.