繁体   English   中英

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

[英]Custom directive: How evaluate bindings with dynamic HTML

设定:

非常简化的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中的绑定? 我试图使用像ngBindTemplate这样的bind几种变体,但是没有用:(

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

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

 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); 
 <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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM