I am trying to pass a $scope\'s variable to a directive, but its not working. I am catching the variable in the template function:
app.directive(\'customdir\', f
Template should not contain logic because template is view. Template should only contain binding directives to make the view updated based on changes of the scope (model). Something like this:
app.directive('customdir', function ($compile) {
return {
restrict: 'E',
scope:{
filterby:"="
},
link:function (scope, element) {
scope.$watch("filterby",function(newValue){ //logic is out of template
if (newValue == "World"){
scope.showCheckBox = true;
}
else {
scope.showCheckBox = false;
}
});
},
template: function(element, attrs) {
//View should be passive and only listens to changes of model to update it accordingly.
return '';
}
};
});
With this approach, you could even change the input at runtime and the view is updated to reflect the changes.
DEMO
If you want to make a decision on which template to use based on some configuration, you should configure it via a normal property, should not access though scope's propery. Simply like this:
app.directive('customdir', function ($compile) {
return {
restrict: 'E',
scope: {
filterby:"=" //filterby is a separate field used for data binding
},
template: function(element, attrs) {
switch (attrs.type) { //view selection configuration should be obtained from the element
case 'checkbox':
return '';
}
return '';
}
};
});
Configure it by passing a normal value:
DEMO