3

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?

4 Answers 4

8

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.

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

4 Comments

I think this will work, but how could I connect the two files? I cannot just do ng-controller="ctrl"
$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>
What is the significance of doing ($scope) at the end??
Dear Bikal Nepal $compile recompile the appended HTML code and apply $scope
3

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'
    });

3 Comments

I understand this, but I have to do it from the controller.js file
Please see my update. Include both these js files in to your html.
In your html, <script type="text/javascript" src="app.js"></script> <script type="text/javascript" src="controller.js"></script>
3

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

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

Comments

2

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>");
 });

Comments