我试图将角度控制器中的对象数组提供给ng-repeat
指令。
数组中返回的对象有几个属性,其中一些可能包含需要由ng-repeat
的结果输出的HTML。我似乎无法弄清楚如何trustAsHTML
返回的整个对象。
我的观点如下:
<li ng-repeat="user in searchedUsers" ng-bind-html="user">
我试过这样的事情:
$scope.searchedUsers = data;
for(var user in $scope.searchedUsers){
$sce.trustAsHtml($scope.searchedUsers[user].matched);
$sce.trustAsHtml($scope.searchedUsers[user].unmatched);
}
还尝试构建我的指令:
<li ng-repeat="user in searchedUsers"><a href="#"><span ng-bind-html="user.matched">{{user.matched}}</span> <span ng-bind-html="user.unmatched">{{user.unmatched}}</span></a></li>
但是我收到了错误:
Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
我使用的JSON对象如下:
[{"id":2,"name":"Jonny","email":"jonnyasmar@me.com","created_at":"2015-10-25 00:58:10","updated_at":"2015-10-25 02:11:59","matched":"jonny<span class=\"match\">as<\/span>mar@me.com","unmatched":"Jonny"}]
知道如何实现这一点或者我是否需要重新考虑我的实施?
答案 0 :(得分:1)
您需要包含ngSanitize js和dependency:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-sanitize.min.js"></script>
和,在模块上:
angular.module('yourModule', ['ngSanitize'])
之后,ng-bind-html将起作用。例如:
<div ng-bind-html="user.matched"></div>
查看jsbin
上的完整代码