gpt4 book ai didi

javascript - AngularJS ng-repeat with ng-bind-html 在数组中呈现 HTML 字符串?

转载 作者:行者123 更新时间:2023-11-30 12:19:28 24 4
gpt4 key购买 nike

我正在尝试呈现来自 HTML 字符串数组的 HTML 字符串,我是 AngularJS 的新手,我试图遵循 AngularJs 网站上的示例,但似乎我无法找到合适的方法这样做的方法。

这是我的 plunker 以便更好地理解,我希望我自己解释了,如果不只是要求更多的澄清。非常感谢您的帮助。

HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example62-production</title>


<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-sanitize.js"></script>
<script src="script.js"></script>



</head>
<body ng-app="bindHtmlExample">
<div ng-controller="ExampleController">
<div ng-repeat="bit in myHTML">
<p ng-bind-html="bit"></p>
</div>
</div>
</body>
</html>

控制者

(function(angular) {
'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
for (i=0; i<6; i++){
$scope.myHTML[i] =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}
}]);
})(window.angular);

PLUNKER EXAMPLE

最佳答案

HTML 文件

<div ng-controller="ExampleController">
<div ng-repeat="bit in myHTML track by $index" >
<p ng-bind-html="bit"></p>
</div>

Javascript 文件

(function(angular) {
'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML = [];
for (var i=0; i<6; i++){
$scope.myHTML[i] =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}
console.log($scope.myHTML)
}]);
})(window.angular);

请引用plunker

"http://plnkr.co/edit/z3KzKPtS1oKGlXI6REm8?p=preview "

解释:

您的代码的问题是循环中的变量i 没有定义。同样在为数组赋值之前,您必须首先初始化该数组。所以 $scope.myHTML = [] 必须在写入值之前写入。

Also ng-repeat does not allow duplicate items in arrays. This is because when there are duplicates, it is not possible to maintain a one-to-one mapping between collection items and DOM elements.

If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.

因此我们必须根据您的需要使用track by $index 来支持重复项。

关于javascript - AngularJS ng-repeat with ng-bind-html 在数组中呈现 HTML 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31512493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com