0

This is my first question so I hope I can explain the situation The angularJs documentation here talks about having the directive templateUrl as a function to be returned dynamically. There is also a Plunkler live demo here.

.directive('....', function() {
   return {
     templateUrl: function(elem, attr){
       return **.... scope.Somthing ...**;
     }
   };
 });

the function does not take a scope parameter and this is the main issue

The only way so far that i found is to set the TemplateUrl dynamically with relevance to the directive scope is this way

.directive('....', function() {
  return {
    link: function (scope, element, attrs) {
      scope.getTemplateUrl = function () {
        return **.... scope.Somthing ...**;
      };
    },
    template: '<ng-include src="getTemplateUrl()"/>'
  };
});

another solution is

.directive('....', function() {
  return {
    controller: function ($scope) {
      $scope.getTemplateUrl = function () {
        return **.... scope.Somthing ...**;
      };
    },
    template: '<ng-include src="getTemplateUrl()"/>'
  };
});

my first issue is that this looks like patch to the problem

my second issue is having to build html string in the directive.

Is there any other way to achive ?

Silvinus
  • 1,445
  • 8
  • 16
  • I'd use a variable instead of a function call in the `ng-include`, but I think what you're doing is perfectly fine. If you're uncomfortable having HTML in the directive, you could always save that snippet to a file instead. This is way simpler than injecting `$compile` and dynamically compiling the template yourself. – adam0101 Jun 23 '16 at 17:01

1 Answers1

0

Lets split your problem for 2 problems :D

First problem is about storing template in js.

This problem can be solved using the $templateCache and injecting

<script id="myTemplate.html" type="text/ng-template"> <div> SOME MARKUP <div> </script>

Here you can read more about this

Second problem is about dynamic templating. So there is 2 solutions (as far as i know :D) First solution you have already mentioned - using ng-include.

Second solution is to use $compile to dynamicly compile html with angular directives.

First solution is little bit better, because in the second case you have to always remember about memory leak. Look here for more info and here

Community
  • 1
  • 1
Drag13
  • 5,859
  • 1
  • 18
  • 42
  • thank for your answer it is very informative. So there is no other good way than the one i have in my quastion?.. I wish the angular team would let the template handle a function with a scope attribute – Maher Hujairi Jun 28 '16 at 16:23
  • Angular team is working with angular 2.0 So I do not think that new features in Angular 1 will come soon. If my answer helps you, please mark it as answer. Ty. – Drag13 Jun 28 '16 at 16:48