我对angularjs很新。
我正在尝试使用AngularJs在视图上显示HTML内容。
我使用ng-model
,但这会在视图中显示HTML内容为字符串。
现在我正在尝试ng-bind-html
,这是第一次工作。
我正在尝试动态追加数据。但数据尚未公布。
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/angular.js" type="text/javascript"></script>
<script src="node_modules/angular-sanitize/angular-sanitize.js" type="text/javascript"></script>
</head>
<body>
<div style="float: right; width: 60%; height: 500px;" ng-app="myApp" ng-controller="myCtrl">
<div ng-bind-html="chatdata"></div>
</div>
<script>
var app = angular.module("myApp", ['ngSanitize']);
var a = "";
app.controller('myCtrl', function ($scope, $sce) {
a += "<div style='float: left; width: 70%'>p1 : data1</div>";
$scope.chatdata = $sce.trustAsHtml(a);
console.log(a);
var i = 2;
var interval = setInterval(function () {
if(i === 22 ) {
clearInterval(interval);
}
if (i % 2 === 0) {
a = a + "<div style='float: right; width: 70%'>p2 : data" + i +"</div>";
$scope.chatdata = $sce.trustAsHtml(a);
} else {
a = a + "<div style='float: left; width: 70%'>p1 : data" + i +"</div>";
$scope.chatdata = $sce.trustAsHtml(a);
}
console.log(a);
console.log($scope.chatdata);
i++;
}, 1000);
});
</script>
</body>
</html>
正如您在屏幕截图中看到的那样,数据只会附加一次。
答案 0 :(得分:2)
不使用 $scope.$apply(function(){
$scope.chatdata
})
并运行完整的摘要周期,请使用
chatdata
仅针对$scope.$apply() i,e complete digest cycle
运行<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.4/angular-sanitize.js" type="text/javascript"></script>
</head>
<body>
<div style="float: right; width: 60%; height: 500px;" ng-app="myApp" ng-controller="myCtrl">
<div ng-bind-html="chatdata"></div>
</div>
<script>
var app = angular.module("myApp", ['ngSanitize']);
var a = "";
app.controller('myCtrl', function ($scope, $sce) {
a += "<div style='float: left; width: 70%'>p1 : data1</div>";
$scope.chatdata = $sce.trustAsHtml(a);
console.log(a);
var i = 2;
var interval = setInterval(function () {
if(i === 22 ) {
clearInterval(interval);
}
if (i % 2 === 0) {
a = a + "<div style='float: right; width: 70%'>p2 : data" + i +"</div>";
$scope.chatdata = $sce.trustAsHtml(a);
} else {
a = a + "<div style='float: left; width: 70%'>p1 : data" + i +"</div>";
$scope.chatdata = $sce.trustAsHtml(a);
}
console.log(a);
console.log($scope.chatdata);
$scope.$apply(function(){
$scope.chatdata
})
i++;
}, 1000);
});
</script>
</body>
</html>
会影响应用程序的性能。
{{1}}
请运行上面的SNIPPET
答案 1 :(得分:1)
尝试使用
$scope.$apply();
在函数结束时为聊天数据赋值后。
答案 2 :(得分:1)
在控制器中注入$ timeout并在分配$ scope.chatdata值时使用它来告诉angular已更新范围
$timeout(function() {
$scope.chatdata = $sce.trustAsHtml(a);
});
工作fiddle