Passing a variable to a 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 does not work. I always end up in the second return statement whether set to disabled or not. I've looked at Passing a Variable Value to an angularjs directive template function , but my use case is slightly different.
source to share
You need to use the service $compile
inside the function of link
your directive.
You need a function that creates the template (say: getTemplate) and then in the link function you use:
element.html(getTemplate(parameter1, parameter2, ...));
Then:
$compile(element.contents())(scope);
Here's an applicable example: http://jsfiddle.net/hwndew2o/4/
source to share
The problem is that when template
used as a function, it takes two arguments: element and attributes objects. There is no region yet.
However, you can 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 are using directives ng-if
to conditionally render the required field based on the property scope.disabled
.
source to share