Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$digest rendering ng-repeat as a comment

I'm writing a test for a directive, when executing the test the template (which is loaded correctly) is rendered just as <!-- ng-repeat="foo in bar" -->

For starters the relevant parts of the code:

Test

...

beforeEach(inject(function ($compile, $rootScope, $templateCache) {

    var scope = $rootScope;
    scope.prop = [ 'element0', 'element1', 'element2' ];

    // Template loading, in the real code this is done with html2js, in this example
    // I'm gonna load just a string (already checked the problem persists)
    var template = '<strong ng-repeat="foo in bar"> <p> {{ foo }} </p> </strong>';
    $templateCache.put('/path/to/template', [200, template, {}]);

    el = angular.element('<directive-name bar="prop"> </directive-name>');
    $compile(el)(scope);
    scope.$digest(); // <--- here is the problem
    isolateScope = el.isolateScope();

    // Here I obtain just the ng-repeat text as a comment
    console.log(el); // <--- ng-repeat="foo in bar" --> 
}));

...

Directive

The directive is fairly simple and it's not the problem (outside the test everything works just fine):

app.directive('directiveName', function () {
    return {
        restrict : 'E',
    replace : true,
    scope : {
        bar : '='
    },
    templateUrl : '/path/to/template', // Not used in this question, but still...
});

A few more details:

  • The directive, outside the test, works fine
  • If I change the template to something far more simple like: <h3> {{ bar[0] }} </h3> the test works just fine
  • The rootScope is loaded correctly
  • The isolateScope results as undefined
like image 515
Abaco Avatar asked Jan 31 '14 11:01

Abaco


1 Answers

If you have a look at the generated output that angular creates for ng-repeat you will find comments in your html. For example:

<!-- ngRepeat: foo in bars  -->

These comments are created by the compile function - see the angular sources:

document.createComment(' ' + directiveName + ': '+templateAttrs[directiveName]+' ')

What you get if you call console.log(el); is that created comment. You may check this if you change the output in this way: console.log(el[0].parentNode). You will see that there are a lot of childNodes: enter image description here

If you use the directive outside of a test you will not be aware of this problem, because your element directive-name will be replaced by the complete created DocumentFragment. Another way to solve the problem is using a wrapping element for your directive template:

<div><strong ng-repeat="foo in bar"> <p> {{ foo }} </p> </strong></div>

In this case you have access to the div element.

like image 145
michael Avatar answered Nov 02 '22 23:11

michael