无法在Angularjs中使用ng-bing进行绑定

时间:2019-03-30 09:08:11

标签: javascript angularjs angularjs-directive angularjs-ng-route ng-bind

尝试使用ng bind如下所示在页面上插入HTML内容,但无法绑定它。

脚本:

SS_Mod_App.controller("SS_Ctrl",/*"$interpolate",*/ function ($scope, $http, $location, $window, $sce/*, $interpolate*/) { 

 $scope.dates = getWeekDates(); //alert(dates); Result: 3/30,3/31, ......

 $scope.divHtmlVar = $sce.trustAsHtml('  <table class="GeneratedTable">  < tbody > <tr>  <td rowspan="2">Cases</td>  <td rowspan="2">Total</td>  <td colspan="3">Mon</td>{{ dates[0] }}   <td colspan="3">Tue</td>{{ dates[1] }}  <td colspan="3">Wed</td> {{ dates[2] }} <td colspan="3">Thu</td> {{ dates[3] }}  <td colspan="3">Fri</td> {{ dates[4] }}  <td colspan="3">Sat</td> {{ dates[5] }}  <td colspan="3">Sun</td>{{ dates[6] }}    </tr>    </tbody >  </table >');

});

HTML页面:

<body>
    <div ng-app="SS_ng_App" ng-controller="SS_Ctrl">
        <div ng-bind-html="divHtmlVar"></div>

    </div>

</body>

无法将它们绑定到HTML {{date [0]}} {{date [1]}} ...

页面中的结果:

< tbody > {{ dates[0] }} {{ dates[1] }} {{ dates[2] }} {{ dates[3] }} {{ dates[4] }} {{ dates[5] }} {{ dates[6] }}
Cases   Total   Mon Tue Wed Thu Fri Sat Sun

1 个答案:

答案 0 :(得分:0)

处理这种情况的一种好方法是通过directive

.directive('render', function($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, element, attrs) {
        scope.$watch(attrs.render, function(html) {
            element[0].innerHTML = html;
            $compile(element.contents())(scope);
        });
    }
};

Here is a plunkr demo

您需要使用$compile来渲染angularjs表达式