I want to use $scope variable in template function of directive like this.
In the other words i want to generate directive template inside of directive and by using $scope variable.
Help me to connect template function to controller.
directive("data", ['$compile', '$http', '$templateCache',function ($http,$rootScope) {
return{
link: function (scope, elem, attrs, ctrl) {
scope.template = something // I want Generate template here
},
template:function(element , attrs){
return $scope.template // I can't access scope here
}
}
You can not access to the scope in the template function, if you want to generate the template somehow and then render the template inside the directive I'll suggest to use the $compile service inside the link function in this way :
var a = angular.module('myApp', []);
a.controller('ctrl', function ($scope) {
$scope.myTemplate = '<span class="custom-tpl"> my template </span>';
});
a.directive('dynamicTemplate', [ '$compile',
function ($compile) {
'use strict';
return {
restrict: 'A',
scope: {
customTemplate: '='
},
link: function ($scope, $element, $attrs, $controller) {
var compiledTemplate = $compile($scope.customTemplate)($scope);
$element.html('').append(compiledTemplate);
}
};
}]);
you can check it out here
The scope
option within directives
provides an isolated scope to remove the scope issues from parent controller and provides the directive to be portable and decoupled with the controller. In your scenario you can define your isolated scope for template as below:
JS Code:
directive("data", ['$compile', '$http', '$templateCache',function ($http,$rootScope) {
return{
restrict: 'EA',
scope: {
template: '='
}
template:function(element , attrs){
return scope.template;
}
}
HTML:
<data template='something'></data>
This way of isolated scope provides the binding strategies ('@', '=')
for one way or two-way data binding of scope variables to DOM. In your case template
attribute in data
element will be two-way data bound to scope
variable template
.