【问题标题】:How do you set controller scope from the result of a signalr request?如何根据信号器请求的结果设置控制器范围?
【发布时间】:2016-02-06 10:53:26
【问题描述】:

我创建了一个简单的信号器集线器,它在称为 hubService 的 angularjs 服务中启动。我能够成功地将 hubService 注入我的控制器。但是,当我调用集线器方法时,它会正确返回一些数据。我无法通过信号器方法回调在控制器内设置 $scope。

/// <reference path="../typings/angularjs/angular.d.ts" />
// The application.
var app = angular.module("app", []);

app.service("hubService", function () {
    this.notification = $.connection.notificationHub;
    $.connection.hub.start();
});

// A controller manages some part of the application.
app.controller("MyController", function ($scope,hubService) {
    $scope.message = "";
    $scope.messageOutput = "";

    hubService.notification.client.addNewMessageToPage = function(message) {
        this.messageOutput = message; // this fails.
    }

    $scope.doSomething = function () {
        hubService.notification.server.send($scope.message);
    }
});

UI代码也很简单,如下:

    <div ng-controller="MyController">
        <input type="text" ng-model="message" />
        <button ng-click="doSomething()">Do Something</button>
        {{ messageOutput }}
    </div>

从信号器回调中正确获取更新范围的最佳方法是什么?

如果我将信号器回调更改为以下代码,我可以获得一些结果。

    hubService.notification.client.addNewMessageToPage = function(message) {
        this.messageOutput = message; // this works but
        this.$apply();                // if I don't have this it is still broken.
    }.bind($scope);
    ...

这并不理想,因为它看起来有点像 hack。

【问题讨论】:

    标签: javascript angularjs model-view-controller signalr


    【解决方案1】:

    使用$apply() 不是黑客。

    当从 Angular 上下文之外的事件或代码更新范围时,有必要告诉 Angular 以便运行摘要以更新视图。

    最好使用$timeout(它在内部调用$apply())以免在摘要已经在进行时遇到冲突。这会将调用推到任何活动摘要周期的结束

    【讨论】:

      猜你喜欢
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2011-08-20
      • 2015-03-23
      相关资源
      最近更新 更多