1

Let's assume the directive myDirective: <my-directive></my-directive>.
When compiled, it should be replaced by the following external template:

<my-button>MyButtonLabel</my-button>

This my-button should be replaced at its own compilation by:

<button class="btn btn-primary">MyButtonLabel</button>

So in a Jasmine test, I invoke the following:

element = angular.element(
                '<directive1></directive1>'
        );
compiledElement = $compile(element)($scope);
$scope.$digest();
console.log(compiledElement); //well displays: <button class="btn btn-primary">MyButtonLabel</my-button>

However, if I place this console.log in the link function itself of the myButton directive, I obtain:

<my-button>MyButtonLabel</my-button>  

The my-button directive isn't recursively compiled !

Is this due to the manual $scope.$digest(); in unit test that would allow the full compilation only at this moment?

In the contrary, when I don't deal with a unit test:
link: function (scope, elm, attrs, ctrl) { console.log(elm); //...
displays the whole compilation.
I imagine this code is executed just before the $scope.$digest();, at this line:

compiledElement = $compile(element)($scope);

I don't think that a JSFiddle/Plunkr would be necessary.
Indeed, I just want to know whether it is a known case in unit testing.

Mik378
  • 21,881
  • 15
  • 82
  • 180

1 Answers1

1

Take a look at this

Working Demo

html

<div ng-controller="Ctrl">
    <my-directive></my-directive>   
<div>

script

app.directive('myDirective', function($compile){
  return {    
    replace: true,    
    transclude: false,
    restrict: 'E',
    scope: false,    
    link: function postLink(scope, iElement, iAttrs) {
            iElement.html('<my-button>MyButtonLabel</my-button>');           
            $compile(iElement.contents())(scope);         
    }
  };  
});

app.directive('myButton', function() {
  return {    
    restrict: 'E',
    template:'<button class="btn btn-primary">MyButtonLabel</button>',
    replace: true
  };  
});

Jasmine Test

Jasmine Test Working Demo

describe('myApp', function () {
    var element;
    beforeEach(function () {
        module('myApp');
        element = angular.element('<my-directive></my-directive>');
        inject(function ($rootScope, $compile) {
            var scope = $rootScope.$new();
            $compile(element)(scope);
            scope.$digest();
        });
    });
    it('says MyButtonLabel', function () {
        expect(element.text()).toBe('MyButtonLabel');
    });
});
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/56068/discussion-between-mik378-and-nidhishkrishnan). – Mik378 Jun 22 '14 at 17:16