我正在使用 Angular JS 来构建一个简单的 Web 应用程序。
我有一个包含多个段落的 JSON 对象。因此我需要将段落分成两行。我做了一些研究,找到了类似问题的一些答案,但因为它们没有放在上下文中,所以我不理解它们。我尝试查看 JSON 中是否内置了强制换行的内容,因为这样就可以了,但我没有找到。
非常感谢您的帮助!
带有 Angular JS 的 HTML
<div class="bio">
{{exhibits[whichItem].bio}}
</div>
JSON
[
{
"name":"Name goes here",
"bio":"First long block of text goes here then it needs a break <br /> and the second long block of text is here."
}
]
AngularJS - Controller .js
var exhibitListControllers = angular.module('exhibitListControllers', ['ngAnimate']);
exhibitListControllers.controller('ListController', ['$scope', '$http', function($scope, $http){
$http.get('js/data.json').success(function(data) {
$scope.exhibits = data;
$scope.exhibitOrder = 'name';
});
}]);
最佳答案
来自https://docs.angularjs.org/api/ng/directive/ngBindHtml
和
https://docs.angularjs.org/api/ngSanitize
ng-bind-html 计算表达式并以安全的方式将生成的 HTML 插入到元素中。默认情况下,生成的 HTML 内容将使用 $sanitize 服务进行清理。要利用此功能,请确保 $sanitize 可用,例如,通过将 ngSanitize 包含在模块的依赖项中(而不是在核心 AngularJS 中)。为了在模块的依赖项中使用 ngSanitize,您需要在应用程序中包含“angular-sanitize.js”。
在 html 页面中你可以这样做
<div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>
在你的 Controller 中:
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}]);
或
您也可以尝试类似的方法:
app.filter('to_trusted', ['$sce', function($sce) { return function(text) { return $sce.trustAsHtml(text); }; }]);
然后,在 View 中:
ng-bind-html=" myHTML | to_trusted"
关于javascript - 将 JSON 字符串格式化为段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46352238/