Shan
Shan

Reputation: 1138

Passing variable to directive template

What I'm trying to do is something like this:

<rule-type-selector class="protractor-test-rule-description" all-rule-types="allRuleTypes" local-value="$parent.$parent.currentRuleDescription" on-selection-change="onSelectNewRuleType()" disabled="disabled">
</rule-type-selector>

And in the directive

  return {
    restrict: 'E',
    scope: {
      allRuleTypes: '&',
      localValue: '=',
      onSelectionChange: '&',
      disabled: '=' 
    },
    template: function($scope) {
      if($scope.disabled) {
        return '<input type="hidden" disabled>';
      }
      return '<input type="hidden">';
    }

This doesn't work. I always hit the 2nd return statement irrespective of whether disabled is set or not. I've looked at Passing value of a variable to angularjs directive template function but my use case seems to be a bit different.

Upvotes: 3

Views: 3199

Answers (2)

Michael
Michael

Reputation: 3326

You need to use the $compile service inside the link function of your directive.

You need a function that creates the template (let's say: getTemplate), then in the link function you use:

    element.html(getTemplate(parameter1, parameter2, ...));

Then:

        $compile(element.contents())(scope);

Here's the applied example: http://jsfiddle.net/hwndew2o/4/

Upvotes: 1

dfsq
dfsq

Reputation: 193261

The problem is that when template is used as a function, it receives two arguments: element and attributes objects. There is no scope yet at this moment.

You can however do something like this in your case:

template: function() {
    return '<input type="hidden" ng-if="disabled" disabled>' + 
           '<input type="hidden" ng-if="!disabled">';
}

So you use ng-if directives to conditionally render necessary field based on scope.disabled property.

Upvotes: 1

Related Questions