从服务器推送 websocket 数据后 Angularjs 模型发生变化 [英] Angularjs model changes after websocket data push from server
问题描述
我正在尝试在从服务器推送 websocket 后更改我的角度模型.每次服务器提供新数据时,如何更改 $scope.contacts
之类的值?
I'm trying to change my angular model after a websocket push from the server. How is it possible to change values like $scope.contacts
each time the server serves new data..?
我不确定使用 $apply
是否可行.我知道我可以访问 DOM 元素检索范围然后更改值,但应该有更好的解决方案!
I'm not sure if it is possible by using $apply
. I know that I can access the DOM element retrieve the scope and then change the values, but there should be a better solution!
我对一种无需创建角度模块即可从外部更新角度模型的解决方案非常感兴趣,因为我使用的是发出更改事件的相关数据源.有没有像在 Backbone.js 中那样简单的方法来做到这一点,你可以说:
I'm really interested in a solution to update the angular model from outside without creating angular modules since I'm using relative data sources that emit change events. Is there no simple way to do that like in Backbone.js where you can say:
var book = new Backbone.Model({ title: 'value' });
book.set("title", "A Scandal in Bohemia");
我想要的 angularjs 是这样的:
What I want in angularjs is something like:
function MyController($scope) {
$scope.contacts = [];
}
datasource changed -> function () {
MyController.set('contacts', 'value'); // change angular scope property
}
推荐答案
看socket.io angular service:
Look at socket.io angular service:
angular.module('app')
.factory('socket', ['$rootScope', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
}]);
和使用它的控制器:
angular.module('app')
.controller('Controller', ['$scope', 'socket', function ($scope, socket) {
socket.emit('register')
socket.on('register', function (data) {
$scope.data = data;
});
}]);
这篇关于从服务器推送 websocket 数据后 Angularjs 模型发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!