Javascript 在更改$scope模型对工厂模型的引用时强制DOM呈现
我正在使用AngularJS 1.2.0通过websocket创建一个简单的消息传递应用程序。HTML在列表上使用ng repeat生成总输出(我输入的消息数组)。我使用工厂托管“私有”数据和方法,并仅公开视图模型和函数来操作控制器中的数据:Javascript 在更改$scope模型对工厂模型的引用时强制DOM呈现,javascript,angularjs,restangular,Javascript,Angularjs,Restangular,我正在使用AngularJS 1.2.0通过websocket创建一个简单的消息传递应用程序。HTML在列表上使用ng repeat生成总输出(我输入的消息数组)。我使用工厂托管“私有”数据和方法,并仅公开视图模型和函数来操作控制器中的数据: <form class="form-search"> <input type="text" ng-model="model.input" class="input-large" placeholder="En
<form class="form-search">
<input type="text" ng-model="model.input" class="input-large"
placeholder="Enter your message:">
<button type="submit" class="btn" ng-click="sendMessage()">Send</button>
</form>
<ul>
<li ng-repeat="message in model.output track by $index" ng-bind="message"></li>
</ul>
application.controller('MessageCtrl', ['$scope', 'MessageService', function($scope, Service) {
$scope['model'] = Service.view;
$scope.sendMessage = function() {
Service.sendMessage();
};
$scope.$watchCollection(function() {
return Service['view'];
}, function(data) {
$scope['model'] = data;
});
}])
.factory('MessageService', function('Restangular') {
var Service = {
// other private properties
view: {
input: null,
output: []
}
};
openConnection();
function openConnection() {
// retrieves websocket URL over Restangular
// opens websocket
}
function sendMessage() {
// sends input over socket
// promises are resolved and unshifted onto Service['view']['output'].
}
return {
view: Service['view'],
sendMessage: function() {
sendMessage();
}
}
});
发送
-
application.controller('MessageCtrl',['$scope','MessageService',function($scope,Service){
$scope['model']=Service.view;
$scope.sendMessage=函数(){
Service.sendMessage();
};
$scope.$watchCollection(函数(){
退货服务[‘查看’];
},函数(数据){
$scope['model']=数据;
});
}])
.factory('MessageService',function('restanglar')){
var服务={
//其他私人物业
视图:{
输入:空,
输出:[]
}
};
openConnection();
函数openConnection(){
//通过Restangular检索websocket URL
//打开websocket
}
函数sendMessage(){
//通过套接字发送输入
//承诺已解析并取消转换到服务['view']['output']。
}
返回{
视图:服务[“视图”],
sendMessage:function(){
sendMessage();
}
}
});
除了当服务['view']中的输出数组获取新消息时,DOM的ng repeat没有更新之外,其他一切都正常工作。我尝试在这个线程中使用$watchCollection作为解决方案,但这也不起作用。唯一可以让DOM重新渲染的方法是通过更改输入文本或触发CSS中的悬停状态来强制DOM重新渲染
在这种设置下,触发摘要的最佳方式是什么,以便在使用新消息数据解析承诺并将其取消转移到输出数组时,DOM立即呈现?我希望避免使用$rootScope和触发事件,因为当其他控制器使用工厂时,这些事件会变得非常不干净。在服务中,我添加了$rootScope依赖项,并使用$rootScope。$apply(),其中承诺将被解析并更新模型
$rootScope.$apply(function() {
Service['view']['output'].unshift(newMessage)
});
这似乎解决了摘要问题,尽管我不确定副作用是什么。在服务中,我添加了$rootScope依赖项,并使用$rootScope。$apply()解决承诺并更新模型
$rootScope.$apply(function() {
Service['view']['output'].unshift(newMessage)
});
这似乎解决了文摘的问题,尽管我不确定副作用是什么