简体   繁体   English

Angular2 $ compile指令作为AngularJS 1

[英]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. 我试图将我自己的项目从angular 1重写为angular 2,我需要compile指令,但是我不能重写它来做与以前相同的工作。

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? 我知道Angular2中没有观察者,但是我有可能在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: HTML:

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

Have in mind that the Test1 and Test2 vars can be changed dynamically at any time. 请记住,可以随时动态更改Test1和Test2变量。

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. Angular 2并没有$compile等效项,我想这是因为它的使用通常表明设计不良。

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. 如果仅从预制的可用组件列表中选择一个要显示的组件就足够了,那么*ngSwitch或路由器都可以胜任。

DynamicComponentLoader is the closest you get. DynamicComponentLoader是最接近的。 With DCL you can insert arbitrary components into the DOM dynamically. 使用DCL,您可以动态地将任意组件插入DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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