Search code examples
javascriptangularjsangularjs-directiveangularjs-ng-routeng-bind

unable bind using ng-bing in Angularjs


Trying to insert HTML content on the page using ng bind as below but unable to bind it.

Script:

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 page:

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

    </div>

</body>

unable to bind these in the HTML {{ dates[0] }} {{ dates[1] }} ...

The result in the page :

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

Solution

  • A good way to handle such case would be via 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

    You need to use $compile to render angularjs expressions