4

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 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can't we do this from controller directly? I know we shouldn't place these kind of functionality in controller, but does it works from controller? just want to know
ya it can work from controller, just you need to compile that element, then append that compiled DOM, instead of doing document.getElementById("page").innerHTML, you can paste same code as I wrote, without click event..but technically you shouldn't do DOM maipulation from controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.