javascript 使用 AngularJS 附加 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33348720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append HTML with AngularJS
提问by Libu Mathew
HTML
HTML
<section>
<div>
<p>{{item}}</p>
</div>
</section>
controller.js
控制器.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?
这是我团队的项目。我无法更改它的设置方式。我试图解决的问题是将 $scope.item 插入到 html 中。我怎么能这样做?
回答by Libu Mathew
I added an id _item in section.
我在节中添加了一个 id _item。
<section id="_item">
<div>
<p>{{item}}</p>
</div>
</section>
Write this below code inside the controller.js file.
在 controller.js 文件中编写以下代码。
angular.element(document.getElementById('_item')).append($compile("<div>
<p>{{item}}</p>
</div>")($scope));
Note: add dependency $compile.
注意:添加依赖项 $compile。
I think this will help you.
我想这会对你有所帮助。
回答by Charlie
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]
[app.js]
myApp = angular.module('myApp', []);
[controller.js]
[控制器.js]
myApp.controller('myController', function($scope){
$scope.item = 'test'
});
回答by Dheeraj Moudgil
Add ng-controller="your_controller_name"
to your HTML.
添加ng-controller="your_controller_name"
到您的 HTML。
<section ng-controller="myController">
<div>
<p>{{item}}</p>
</div>
</section>
回答by JoSeTe4ever
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
答案的标题可能具有误导性。如果你真的想用 Angular JS 附加 HTML,我认为你需要的是 ng-bind-html 指令
https://docs.angularjs.org/api/ng/directive/ngBindHtml
https://docs.angularjs.org/api/ng/directive/ngBindHtml
your html code should be something like
你的 html 代码应该是这样的
<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>");
});