generate dynamic html on ng click

2019-02-23 08:20发布

问题:

I want to insert dynamic html element which contains ng-bind and directive on ng-click. I want to insert new html elements inside

Html looks like this

     <body data-ng-controller="controller">
         <div id="toolbox">
             <label>Page Width</label>
             <input type="text" data-ng-model="pageWidth" />
             <input type="button" value="H1" data-ng-click="createH1()" />
         </div>
         <div id="editor">
             <div data-ng-style="{width:pageWidth + 'px'}" data-ng-page>

             </div>

         </div>
    </body>

Controller >

    app.controller('controller', ['$scope', function ($scope) {
        $scope.createH1 = function () {
            document.getElementById("page").innerHTML = document.getElementById("page").innerHTML + ("<div class='h1' data-ng-h1 draggable></div>");
        };
    }]);

The above controller is inserting html element, but the directives of new html elements are not working.

However I came to know that unless we $compile template/html they'll not work.
If I use app.directive( ngPage, ..) to add my dynamic html, it is inserting while app is started. But I want to insert only on button ng-click.

I'm new to angular js, a bit confused please help me out with this. Thanks in advance.

回答1:

I will Always prefer to do DOM manipulation from directive. So here code will look like below

HTML

  <body ng-controller="MainCtrl as vm">
    <button add-html>click me</button>
    <div id="page">
      This will be replaced by text
    </div>
  </body>

CODE

app.directive('addHtml', function($compile){
  return {
    restrict: 'AE',
    link: function(scope, element, attrs){
      var html = `<div class='h1' data-ng-h1 draggable>Test</div>`,
      compiledElement = $compile(html)(scope);

      element.on('click', function(event){
        var pageElement = angular.element(document.getElementById("page"));
        pageElement.empty()
        pageElement.append(compiledElement);
      })
    }
  }
});

Plunkr Here