自定义指令:如何使用动态HTML评估绑定

时间:2015-02-12 18:25:06

标签: javascript angularjs angularjs-directive eval

设定:

非常简化的HTML:

<td ng-repeat="col in cols">
    <div ng-bind-html="col.safeHTML"></div>
</td>

JS控制器:

$scope.cols = [
    {
      field       : 'logo',
      displayName : 'Logo',
      cellTemplate: '<div style="color:red">{{col}}</div>'
    },
    {
      field       : 'color',
      displayName : 'Color',
      cellTemplate: '<div style="color:green">{{col}}</div>
    }
  ];

JS链接指令链接功能:

        for (var i = 0, j = $scope.cols.length;
               i < j;
               i++) {

            if ($scope.cols[i].hasOwnProperty('cellTemplate')) {
              $scope.cols[i].safeHTML = $sce.trustAsHtml($scope.cols[i].cellTemplate);
            }
          }

它正确地转义HTML但绑定({{some_var}})没有被插值。

如何让Angular在安全的HTML中计算绑定?我尝试使用bind的几种变体,例如ngBindTemplate,但没有用:(

1 个答案:

答案 0 :(得分:1)

如果您计划动态编译角度组件并手动将它们添加到DOM,您实际上想要使用$compile服务。

通过一些自定义指令工作,您可以非常轻松地完成这项工作。

&#13;
&#13;
function compileDirective($compile) {

  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      //Watch for changes to expression
      scope.$watch(attrs.compile, function(newVal) {

        //Compile creates a linking function
        // that can be used with any scope
        var link = $compile(newVal);

        //Executing the linking function
        // creates a new element
        var newElem = link(scope);

        //Which we can then append to our DOM element
        elem.append(newElem);
      });
    }
  };

}


function colsController() {
  this.cols = [{
    name: "I'm using an H1",
    template: "<h1>{{col.name}}</h1>"
  }, {
    name: "I'm using an RED SPAN",
    template: "<span style=\"color:red\">{{col.name}}</span>"
  }];
}

angular.module('sample', [])
  .directive('compile', compileDirective)
  .controller('colsCtrl', colsController);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.4/angular.min.js"></script>
<div ng-app="sample">

  <ul ng-controller="colsCtrl as ctrl">
    <li ng-repeat="col in ctrl.cols">
      <!-- The "compile" attribute is our custom directive -->
      <div compile="col.template"></div>
    </li>
  </ul>

</div>
&#13;
&#13;
&#13;