小编典典

在元素内插入一个有角度的js模板字符串

angularjs

我试图在元素中放入一些有角度的js模板字符串,并期望得到编译的输出。但这没有发生。

HTML

<div ng-controller="testController">
    <div ng-bind-html-unsafe="fruitsView"></div>
</div>

控制器:

function filterController($scope){
    ...
    $scope.arr = ["APPLE", "BANANA"];
    $scope.fruitsView = '<div><p ng-repeat="each in arr">{{each}}</p></div>';
}

输出是正义的{{each}}

那么如何$scope.fruitsView在元素内插入一个有角度的js模板字符串(here )?

我为此做了一个小提琴


阅读 254

收藏
2020-07-04

共1个答案

小编典典

在这种情况下,您不希望仅“插入HTML”,而是对其进行编译。您可以使用该$compile服务创建DOM节点。

var tpl = $compile( '<div><p ng-repeat="each in arr">{{each}}</p></div>' )( scope );

如您所见,$compile返回一个函数,该函数将范围对象作为参数,对代码进行评估。element.append()例如,可以使用将结果内容插入DOM

重要说明 :但是在 任何情况下 ,控制器中都不会包含任何与DOM相关的代码。正确的地方 始终
是指令。可以将这些代码轻松地放入指令中,但是我不知道为什么您要以编程方式完全插入HTML。

您能否在这里阐明一些信息,以便我提供更具体的答案?

更新资料

假设您的数据来自服务:

.factory( 'myDataService', function () {
  return function () {
    // obviously would be $http
    return [ "Apple", "Banana", "Orange" ];
  };
});

您的模板来自服务

.factory( 'myTplService', function () {
  return function () {
    // obviously would be $http
    return '<div><p ng-repeat="item in items">{{item}}</p></div>';
  };
});

然后,您创建一个简单的指令,该指令读取提供的模板,对其进行编译,然后将其添加到显示中:

.directive( 'showData', function ( $compile ) {
  return {
    scope: true,
    link: function ( scope, element, attrs ) {
      var el;

      attrs.$observe( 'template', function ( tpl ) {
        if ( angular.isDefined( tpl ) ) {
          // compile the provided template against the current scope
          el = $compile( tpl )( scope );

          // stupid way of emptying the element
          element.html("");

          // add the template content
          element.append( el );
        }
      });
    }
  };
});

然后从您的角度来看:

<div ng-controller="MyCtrl">
   <button ng-click="showContent()">Show the Content</button>
   <div show-data template="{{template}}"></div>
</div>

在控制器中,您只需将其捆绑在一起:

.controller( 'MyCtrl', function ( $scope, myDataService, myTplService ) {
  $scope.showContent = function () {
    $scope.items = myDataService(); // <- should be communicated to directive better
    $scope.template = myTplService();
  };
});

它应该一起工作!

PS:这都是假设您的模板来自服务器。如果不是,则您的模板应位于指令中,这可以简化操作。

2020-07-04