javascriptangularjsdata-bindingng-bind-htmlangularjs-compile

I am getting issue in changing inner HTML of div


I found a problem in changing html of div:

document.getElementsByClassName("lab")[0].setAttribute("ng-bind-html", "binds"); 
$scope.binds="<h1>run</h1>";

I am setting attribute ng-bind-htmlin java script because I have have integrated some plugin in my code in which div of class="lab" is getting declared through JavaScript. The attribute binds is attached properly, I checked this in inspect element. In fact whenever I attached property of ng-bind-html in JavaScript then ng-bind-html does not work. What is the correct way to do it? There is no error in the code.


Solution

  • Basically you have added ng-bind-html attribute dynamically, which will add directive attribute to the DOM but ng-bind-html directive wouldn't get evaluated the html content. You need to recompile that DOM using

    $compile(document.getElementsByClassName("lab")[0])($scope)
    

    To making sure this should work you need to add ngSanitize module in your angular app.

    Demo plunkr

    The way you are doing is not a standard way of doing DOM manipulation in AngularJS. The standard approach would be keep ng-bind-html attribute there itself in html rather than adding it dynamically.

    Standard way

    HTML

    <h1>Cleaner way</h1>
    <pre ng-bind-html="binds"></pre>
    

    Code

    (function(angular) {
      'use strict';
      angular.module('bindHtmlExample', ['ngSanitize'])
        .controller('ExampleController', ['$scope', '$compile', function($scope, $compile) {
          $scope.binds="<h1>run</h1>";
    
        }]);
    })(window.angular);
    

    Plunkr