Append HTML with AngularJS

19,595

Solution 1

I added an id _item in section.

<section id="_item">
  <div>
     <p>{{item}}</p>
  </div>
</section>

Write this below code inside the controller.js file.

angular.element(document.getElementById('_item')).append($compile("<div>
     <p>{{item}}</p>
  </div>")($scope));

Note: add dependency $compile.

I think this will help you.

Solution 2

This is one of the most basic ways to do it.

angular.module('myApp', [])

.controller('myController', function($scope){
     $scope.item = 'test'
});


<div ng-app="myApp" ng-controller="myController">
     <p>{{item}}</p>
</div>

UPDATE

[app.js]

myApp = angular.module('myApp', []);

[controller.js]

myApp.controller('myController', function($scope){
         $scope.item = 'test'
    });

Solution 3

Add ng-controller="your_controller_name" to your HTML.

<section ng-controller="myController">
  <div>
     <p>{{item}}</p>
  </div>
</section>

Solution 4

The title of the answer might be missleading. If you really want to append HTML with Angular JS, I think what you need is the ng-bind-html directive

https://docs.angularjs.org/api/ng/directive/ngBindHtml

your html code should be something like

<section>
  <div>
   <p ng-bind-html="item"></p>
  </div>
 </section>

the following conf in your controller

.controller('myController','$sce' function($scope, $sce){
 $scope.item = $sce.trustAsHtml("<div> this is really appending HTML using AngularJS </div>");
 });
Share:
19,595

Related videos on Youtube

Charlie
Author by

Charlie

Please leave a comment with your down votes. So, I can make sure you are not disappointed next time.

Updated on August 15, 2022

Comments

  • Charlie
    Charlie over 1 year

    HTML

    <section>
      <div>
         <p>{{item}}</p>
      </div>
    </section>
    

    controller.js

    (function () {
       var ctrl = function ($scope){
            $scope.item = "test";
       }
    }());
    

    This is my team's project. I cannot change how it is set up. The problem I am trying to solve is inserting the $scope.item into the html. How could I do this?

  • Admin
    Admin over 8 years
    I think this will work, but how could I connect the two files? I cannot just do ng-controller="ctrl"
  • Libu Mathew
    Libu Mathew over 8 years
    $scope.bindHtml =function(){angular.element(document.getElementById('_item')‌​).append($compile("<‌​div> <p>{{item}}</p> </div>")($scope)); }; // call the function in ng-init="bindHtml" in the html page. <div ng-controller="[YOURCONTROLLER NAME]" ng-init="bindHtml()"><section id="_item"></section></div>
  • Bikal Nepal
    Bikal Nepal over 5 years
    What is the significance of doing ($scope) at the end??
  • Syed Nasir Abbas
    Syed Nasir Abbas about 4 years
    Dear Bikal Nepal $compile recompile the appended HTML code and apply $scope