Home Ask Login Register

Developers Planet

Your answer is one click away!

v1nc3nz00 February 2016

Angularjs directive template = $scope.(some variable from another controller)

This is part of my AngularJS application

  .controller('Littlebear',function($scope) {
        $scope.spread='<h1>this is the</h1> Littlebear spread.'+
        '<img ng-src="src/images/retro.png" alt="picture" ng-click="click()">';
    })
   .directive('spread', function($compile) {
     var templateTemp='<p> try again </p>';
      var directive = {};


      directive.compile = function(element, attributes) {

   var linkFunction = function($scope, element, atttributes) {
       // bind element to data in $scope
       templateTemp=$scope.spread;
       return templateTemp;
   };

   return linkFunction;
   };

directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = templateTemp;
return directive;
    })

I would like to set template = $scope.spread inside the directory.

If I console.log the templateTemp inside the linkFunction the value of templateTemp is exacly what I am looking for but ouside of that function is templateTemp='

try again

';

can anyone suggest any solution?

(PS: as you might imagine I am quite new to AngularJS)

Thanks Vincent

Answers


Ganesh February 2016

In link function you can do something as below. In link function, I have compiled the desired html and replaced the directive element with the same.

.controller('Littlebear',function($scope) {
        $scope.spread='<h1>this is the</h1> Littlebear spread.'+
        '<img ng-src="src/images/retro.png" alt="picture" ng-click="click()">';
    })
   .directive('spread', function($compile) {
     var templateTemp='<p> try again </p>';
      var directive = {};


      directive.compile = function(element, attributes) {

   var linkFunction = function($scope, element, atttributes) {

				// you can change and compile the html like this
				//element.replaceWith($compile($scope.spread)); //Please Check this line<-----

//Please try this.
 var html =$scope.spread;
        var e =$compile(html)($scope);
        element.replaceWith(e);
				
   };

   return linkFunction;
   };

directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = templateTemp;
return directive;
    })

Post Status

Asked in February 2016
Viewed 3,569 times
Voted 7
Answered 1 times

Search




Leave an answer


Quote of the day: live life