简体   繁体   中英

Angular2 $compile directive as AngularJS 1

Im trying to rewrite my own project from angular 1 to angular 2 and i need compile directive, but i cant rewrite it to do the same job as before.

app.directive("compile", compile);
compile.$inject = ["$compile"];
function compile($compile) {
    return function ($scope, element, attrs) {
        $scope.$watch(
          function ($scope) {
              return $scope.$eval(attrs.compile);
          },
          function (value) {
              element.html(value);
              $compile(element.contents())($scope);
          }
        );
    };
}

I know there is no watchers in Angular2, but is there any chance i can receive the same functionality in Angular2?

And i need to work with data like this (i mean compile with child compile directive too):

Controller:

function Controller($scope) {
    $scope.Test1 = '<div compile="Test2"></div>';
    $scope.Test2 = '<h1>Test!</h1>';
}

HTML:

<div compile="Test1"></div>

Have in mind that the Test1 and Test2 vars can be changed dynamically at any time.

The whole thing should print as result:

<div compile="Test1">
    <div compile="Test2">
        <h1>Test!</h1>
    </div>
</div>

Angular 2 does not have any equivalent of $compile , intentionally, I would guess because its use is usually an indicator of bad design.

What do you need it for? Do you truly need the ability to dynamically insert absolutely anything in your template? If simply choosing one component to display from a premade list of available components is enough, then either *ngSwitch or a router can do the job.

DynamicComponentLoader is the closest you get. With DCL you can insert arbitrary components into the DOM dynamically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM