【问题标题】:how to insert an angular 1.5 component with ng-bind-html如何使用 ng-bind-html 插入 Angular 1.5 组件
【发布时间】:2017-02-23 03:55:10
【问题描述】:

我有一个组件,我想将它动态注入到我的 html 中。

我有一个这样的组件:

angular.module('test1', []);

angular.module('test1').component('test1', {
    templateUrl: 'components/test1/test1.template.html',
    controller: function test1Controller($scope) {
    }
});

test1.template.html 文件如下所示:

<p>TEST 1</p>

在我的控制器上我有这个:

angular.module('myApp')
  .controller('ctrlCtrl', function ($scope, $sce) {
    $scope.tag = "<test1/>";
  });

在我的index.html 上,我有这个:

<ng-bind-html ng-bind-html="tag"></ng-bind-html>

但标签不会显示。我尝试在ng-bind-html 字段上写字面意思"'&lt;p&gt;hi!&lt;/p&gt;'",并写上“嗨!”出现在一个段落上,所以我认为这个错误不是因为错字。

我也尝试使用$sce.trustAsHtml,但也没有用:(

$scope.tag = $sce.trustAsHtml("<test1/>");

当我插入一个输入字段时,trustAsHtml 方法确实有效,但是当我尝试动态注入我的组件时,它就是不允许我,请帮助 D:

【问题讨论】:

  • ng-bind-html 不编译指令。为什么要采取这种迂回的方式?
  • 真的吗?哎呀,太可怕了!...我有一个组件库,用户可以将这些组件拖到一个地方,以便创建一个包含所有这些组件的布局。基本上,我想动态创建组件来实现这一点:(
  • 不难用$compile自己编译

标签: angularjs components


【解决方案1】:

为什么ng-include 不起作用?

组件需要先编译才能在标记上使用。尝试使用浏览器中的开发人员工具编辑应用程序的 html,方法是在标记上人为注入您的组件:它不会工作。

如何动态包含组件?

你需要使用指令,这个tutorial(感谢@Artem K.)很容易理解,但你也可以阅读angular's official documentation,虽然有点难以理解。

按照 angular 官方文档最后一个示例的逻辑,您可以创建一个指令来编译传递给它的所有内容,如下所示:

// source: https://docs.angularjs.org/api/ng/service/$compile
angular.module('myApp')
  .directive('my-compile', function ($compile) {
    return function(scope, element, attrs) {
      scope.$watch(
        function(scope) {
          // watch the 'compile' expression for changes
          return scope.$eval(attrs.compile);
        },
        function(value) {
          // when the 'compile' expression changes
          // assign it into the current DOM
          element.html(value);

          // compile the new DOM and link it to the current
          // scope.
          // NOTE: we only compile .childNodes so that
          // we don't get into infinite loop compiling ourselves
          $compile(element.contents())(scope);
        }
      );
    };
  });

然后,在您的index.html 上,您必须调用指令,发送包含组件标签的字符串作为参数。

<div compile="tag"></div>

正如@charlietfl 和@Artem K. 所说,您必须了解角度的​​$compile 所以,感谢大家指出我正确的方向:)

【讨论】:

  • 非常感谢!在坚持了 3 天之后,您的回答成功了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 2013-06-14
  • 1970-01-01
  • 2015-02-06
  • 2013-01-21
  • 2017-05-16
相关资源
最近更新 更多