链接在ng-repeat中编译html

时间:2014-11-25 21:39:15

标签: angularjs angularjs-directive angularjs-compile

我一直在寻找这个问题的几个小时,我似乎无法在这里解决一个解决方案。

我正在尝试创建一个能够呈现HTML功能的指令。我认为通过$ compile运行HTML就足够了,但看起来它只有1级深度。

如何编译数据的rawHtml部分以便ng-click有效?

**编辑:我想出了如何使用angular sanitize返回HTML,但是,它仍然没有编译。如何将其编译到范围?

Plunker:http://plnkr.co/edit/f9nxHlbRThzSHoD3Awhp?p=preview

<body ng-app='testApp'>
  <div ng-controller='testCtrl'>
    <test-directive ng-model='dataItems'></test-directive>
  </div>
</body>      

和JS

var app = angular.module('testApp', ['ngSanitize']);

app.controller('testCtrl', ['$scope', function($scope) {
  $scope.dataItems = [
      { name: 'Test1', rawHtml: '<input type="button" ng-click="onClick(1);" value="Click 1" />' },
      { name: 'Test2', rawHtml: '<input type="button" ng-click="onClick(2);" value="Click 2" />' }
    ]
}]);

app.directive('testDirective', ['$compile', '$sce', function($compile, $sce) {
  return {
    restrict: 'E',
    scope: {
      ngModel: "="
    },
    template: "<ul><li ng-repeat='item in ngModel'><div ng-bind-html=\"getHtml(item.rawHtml)\">{{item.name}}</div></li></ul>",
    controller: function($scope) {
      $scope.onClick = function(num) {
        console.log(num);
      }

      $scope.getHtml = function(html) {
        return $sce.trustAsHtml(html); 
      }
    }
  }
}])

1 个答案:

答案 0 :(得分:3)

实际上你应该尽可能地避免它。它可以在非常罕见的情况下完成并且使用非常小心。

在AngularJS方式中,您应该提供所有可能的视图,并且不要在JS代码中放置任何视图逻辑。您可以添加不同的模板,您可以使用ng-switch / ng-if选择其中一个选项。

但如果你真的需要它,你可以确实使用$compile。您可以使用指令:

app.directive('compile', function($compile) {
  return {
    restrict:'A',
    link: function(scope, element, attr) {
      element.append($compile(attr.compile)(scope));
    }
  }  
})

并将其用作

<div compile="{{item.rawHtml}}">

Plunker:http://plnkr.co/edit/6vNg5fP5yfOsATmSkReg?p=preview

小心使用。我不建议将此指令用于一般用途。

相关问题