Angular dynamic templating with VS template compilation function?

I already know what the purpose of each element is: compilevs link(pre/post)vscontroller

So let's say I have this simple code:

HTML

  <body ng-controller="mainController">
    {{ message }}
    <div otc-dynamic=""></div>
  </body>

Controller

app.controller("mainController", function($scope) {
  $scope.label = "Please click";
  $scope.doSomething = function() {
    $scope.message = "Clicked!";
  };

});

Directive

app.directive("otcDynamic", function($compile) {

  var template = "<button ng-click='doSomething()'>{{label}}</button>";

  return {

    compile: function(tElement, tAttributes) {
        angular.element(tElement).append(template);
        for (var i = 0; i < 3; i++) {
          angular.element(tElement).append("<br>Repeat " + i + " of {{name}}");
        }

        return function postLink(scope, element, attrs) {
          scope.name = "John";
        }
      }

  }
});

So, as we see, I change the template (in the function compile- where it should actually be)

Result ( plnker ):

But

I did not know that template:...it could also accept a function.

So, I could use the template( plunker ) function :

app.directive("otcDynamic", function() {

  var template1 = "<button ng-click='doSomething()'>{{label}}</button>";

  return {
    template: function(element, attr) {
      element.append(template1);
      for (var i = 0; i < 3; i++)
        element.append("<br>Repeat " + i + " of {{name}}");

    },

    link: function(scope, element) {
      scope.name = "John";
    }
  }
}); 

Question

If so - when should the templatevs function be used compile?

+4
source share
1

, .

- DOM Angular. DOM . , , . template, compile link - . compile template, link.

A)

, HTML- , DOM . HTML-. . , - HTML, DOM. , DOM.

B)

- , HTML DOM HTML . Angular DOC

HTML- DOM , .

, - . , , template, , . https://docs.angularjs.org/api/ng/service/ $compile

C)

, $watch, $apply .., Angular, . - , link, , . Angular , , . dom DOM jQlite

,

1. DOM HTML. HTML.

2. - HTML . HTML .

3. - . html , .

, .

+1

Source: https://habr.com/ru/post/1614230/


All Articles