javascript 从服务器推送 websocket 数据后 Angularjs 模型发生变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14702981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:20:59  来源:igfitidea点击:

Angularjs model changes after websocket data push from server

javascriptwebsocketangularjssocket.io

提问by Pascal Bayer

I'm trying to change my angular model after a websocket push from the server. How is it possible to change values like $scope.contactseach time the server serves new data..?

在从服务器推送 websocket 后,我​​试图更改我的角度模型。$scope.contacts每次服务器提供新数据时如何更改值..?

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!

我不确定是否可以使用$apply. 我知道我可以访问 DOM 元素检索范围然后更改值,但应该有更好的解决方案!

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:

我对从外部更新角度模型而不创建角度模块的解决方案非常感兴趣,因为我使用的是发出更改事件的相关数据源。有没有像在 Backbone.js 中那样简单的方法来做到这一点,你可以说:

var book = new Backbone.Model({ title: 'value' });
book.set("title", "A Scandal in Bohemia");

What I want in angularjs is something like:

我想要的 angularjs 是这样的:

function MyController($scope) {
    $scope.contacts = [];
}

datasource changed -> function () {
    MyController.set('contacts', 'value'); // change angular scope property
}

回答by Maxim Grach

Look at socket.io angular service:

查看 socket.io 角度服务:

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);
            }
          });
        })
      }
    };

  }]);

and controller using it:

和使用它的控制器:

angular.module('app')
  .controller('Controller', ['$scope', 'socket', function ($scope, socket) {

    socket.emit('register')

    socket.on('register', function (data) {
        $scope.data = data;
    });

}]);

回答by Ajay Beniwal

just do it like below

就像下面那样做

 socket.onmessage = function (event) {
     scope.$apply(function(){
       // modify scope values here 
     }
    };

回答by Jimbo

Well, the marked answer is certainly not a "simple way" as requested by OP. Here's a much simpler solution.

好吧,标记的答案肯定不是 OP 要求的“简单方法”。这是一个更简单的解决方案。

Retrieve the scope wherever you want in your own JavaScript code:

在您自己的 JavaScript 代码中的任何位置检索范围:

var scope = angular.element($("#elementID")).scope();

Change a value in your Angular $scopevariable, but from your external JavaScript:

更改 Angular$scope变量中的值,但来自外部 JavaScript:

scope.$apply(function() {
    scope.yourArrayForExample.push({name: 'New, external value'});
});

Here's a JSFiddle.

这是一个JSFiddle