Search code examples
angularjsangularjs-scopeangular-directive

Directive's link is not rendering variable in the scope


I'm expecting the directive to print the template with the values inside {{ }} resolved, but it's not. It's printing out {{argVal}} as if it's a literal piece of HTML string.

myApp.directive('myArgs', [function() {

    var theTemplate = 
        '<span>{</span>' + 
            '<div ng-if="typeIsArray(argVal)">'+
                '<p>{{argVal}}</p>'
                '<my-args arg-val="argVal[0]"></my-args>'
            '</div>';

    return {
        restrict: "E",
        scope: {
            argVal: '='
        },
        controller: ... //contains utils to check type of argVal
        link: function(scope, element){
            alert(scope.argVal);
            element.html('').append(theTemplate);
        }
      };        
}]);

In my HTML file, I'm simply calling the directive like this:

<my-args arg-val="someArray"></my-args> 

(someArray is defined in the controller as $scope.someArray = ["ola", "hi", "bonjour"];)

someArray is definitely in the scope because the alert(someArray) is working.

So why won't the template portion render properly?


Solution

  • You need to compile the template with scope

    element.html('').append(theTemplate);
    $compile(element.contents())(scope);
    

    And dont forget to provide dependency $compile to directive.