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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments