最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Append HTML with AngularJS - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Oct 26, 2015 at 15:04 Charlie 23.8k12 gold badges63 silver badges95 bronze badges asked Oct 26, 2015 at 14:50 user4211162user4211162
Add a comment  | 

4 Answers 4

Reset to default 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.

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

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

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

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>");
 });
发布评论

评论列表(0)

  1. 暂无评论