【问题标题】:Angular: How to dynamically add components to html in an string, and bootstrap it?Angular:如何在字符串中动态地将组件添加到 html 并引导它?
【发布时间】:2016-07-22 14:17:38
【问题描述】:

我想这样做:

你有这样的代码:

<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}}

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

如果您设置&lt;body&gt;&lt;hello-world&gt;&lt;/hello-world&gt;&lt;/body&gt; 并加载文档,这将非常有效,我想设置组件并在首先加载 web 后加载它。

【问题讨论】:

  • 尝试在 ng-if="myFunction()" 或 addCode() 设置的值 $scope.myvalue 上执行函数
  • 我想不出有任何理由这样做,因为使用 ng-if 不会做得更好。你真的不应该用 jQuery 任意注入 Angular 组件。

标签: php jquery angularjs twitter-bootstrap


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    解决了!

    这是代码,我终于搞定了,没那么难。

    在你的脚本中:

    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>
    

    在你的 html 主文件或布局中:

    <hello-world></hello-world>
    

    :)

    【讨论】:

      猜你喜欢
      • 2013-08-21
      • 1970-01-01
      • 2021-07-22
      • 2022-08-17
      • 2013-06-16
      • 1970-01-01
      • 2016-11-29
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多