我使用的是最新版本的Angular JS - 1.2,我有一个包含
属性的对象的数组,如下所示:first second last
而不是单个空格。如何让Angular用“”替换它们?我曾尝试使用ng-bind-html
,但似乎无效。
我的控制器:
app.controller('ChatController', ['$scope', '$http', function ($scope, $http) {
$scope.messages = [];
var setMessages = function (data) {
$scope.messages = data || [];
};
$http.get(url).success(setMessages)
}
我使用Jade的观点:
ul#chat
li(ng-repeat="message in messages")
span.name(ng-bind-html="message.by")
span.message {{message.text}}
当我尝试使用ng-bind-html时出现此错误:
Error: [$sce:unsafe]
at Error (native)
at http://localhost/libraries/angular/angular.min.js:6:450
at $get.e (http://localhost/libraries/angular/angular.min.js:117:34)
at $get.getTrusted (http://localhost/libraries/angular/angular.min.js:118:327)
at Object.$get.e.(anonymous function) [as getTrustedHtml (http://localhost/libraries/angular/angular.min.js:120:71)
at Object.fn (http://localhost/libraries/angular/angular.min.js:192:234)
at k.$get.k.$digest (http://localhost/libraries/angular/angular.min.js:109:213)
at k.$get.k.$apply (http://localhost/libraries/angular/angular.min.js:112:173)
at h (http://localhost/libraries/angular/angular.min.js:72:300)
at w (http://localhost/libraries/angular/angular.min.js:77:288)
答案 0 :(得分:1)
html被认为是'不安全的' by angular将被转义(即$nbsp;
将被字面上呈现为空白)
将模块依赖项添加到ngSanitize
,并向控制器添加对$sce
.controller(' ChatController',[[' $ scope',' $ http',function($ scope,$ http){ $ scope.messages = [];
var setMessages = function (data) {
angular.forEach(data, funciton(msg) {
$sce.trustAsHtml(msg.text);
});
$scope.messages = data || [];
};
$http.get(url).success(setMessages);
}])
$sce.trustAsHtml(msg.text)
调用将文本标记为"信任"所以angular将它呈现为HTML
答案 1 :(得分:0)
我能用过滤器给他们充电
app.filter('removeNonBreakingSpaces', function () {
return function (text) {
return text.replace(/ /g, ' ');
}
});
ul#chat
li(ng-repeat="message in messages")
span.message {{message.text | removeNonBreakingSpaces}}