Angular:如何在字符串中动态地向html添加组件,并引导它


Angular: How to dynamically add components to html in an string, and bootstrap it?

我想这样做:

你有一个这样的代码:

<body ng-app="MyApp">
<div id="content"><button onclick="addCode()">Add Code</button></div>
</body>

现在,函数"addCode()"正在执行以下操作:(使用jQuery库)

function addCode(){
  $("content").html("<hello-world></hello-world>");
}

这个标签是一个有角度的组件,代码:

'use strict';
        angular.module('MyApp', []).component('helloWorld', {
            templateUrl: 'template.html',
            controller: function () {
                this.greet = 'Hello World';
            }
});

最后,template.html有下一个代码:

<p>{{$ctrl.greet}}</p>

我如何让该脚本在单击按钮后启动应用程序,以便在网页中的段落中显示"Hello World",而不是{{$ctrl.greet}}

换句话说,我想让angular重新加载/重新引导文档搜索组件标签,以动态加载它们。

如果您设置<body><hello-world></hello-world></body>并加载文档,这将非常有效,我希望设置组件并在首先加载web后加载它。

在Angular之外进行DOM更改时,需要通知Angular。这可以通过$scope来完成$digest()命令。

已解决!

这就是代码,最终我明白了,没那么难。

在您的脚本中:

angular.module('MyApp', []).component('helloWorld', {
        templateUrl: 'template.html',
        controller: function ($http) {
            var ctrl = this;
            ctrl.updateHello = function (str) {                    
                ctrl.greet = 'Hello '+str;
            };
            ctrl.updateHello('World')
        }
});

在你的html模板中:

<button class="ng-binding" ng-click="$ctrl.updateHello ('Angular')">UPDATE</button>
<div>{{$ctrl.greet}}</div>

在ur-html主文件或布局中:

<hello-world></hello-world>

:)