我已经在AngularJS中构建了一个应用程序,它按预期工作,但是,我遇到了性能问题,因为它为我的聊天(使用ng-repeat)重新渲染了DOM关于范围变化的变量。
我已经能够在 this plunkr 中重现这一点。
为什么这样做?如何在$scope.messages
更改时仅将其重新呈现给消息日志?此外,如何在对$scope.messages
进行更改时更新新元素或不同元素?
的index.html:
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" data-semver="1.4.6"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>How can I prevent Angular from rerendering the chat log everytime another var on the scope is changed?</p>
<p>Furthermore, how can I make it only add the new value when a message is added rather than rerendering the entire message log?</p>
<ul>
<li ng-repeat="msg in messages track by $index">
{{ msg.name }}: <span ng-bind-html="trustAsHtml(msg.message)"></span>
</li>
</ul>
<button ng-click="incRandomVar()">Update Unrelated Variable {{ randomVar }}</button>
<button ng-click="addMessage()">Add new message</button>
</body>
</html>
app.js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $sce) {
$scope.randomVar = 1;
$scope.incRandomVar = function () {
$scope.randomVar += 1;
};
$scope.messages = [
{name: "John", message: "Hello world, give <a href=\"http://google.com\">Google</a> a try!"},
{name: "World", message: "Google? What's that?"},
{name: "World", message: "Wahooa, this looks cool!"},
{name: "John", message: "They call it a \"Search Engine\", you can find anything on there!"}
];
$scope.addMessage = function () {
$scope.messages.push({name: "System", message: "This is a system message"});
};
$scope.trustAsHtml = function (message) {
console.log('Rerendering message:', message);
return $sce.trustAsHtml(message);
}
});
修改:这似乎是由于在&#39;内调用了一个功能(trustAsHtml
)。 ngRepeat。但是,我无法在不调用它的情况下呈现HTML ...如何在不影响性能的情况下解决这个问题?