【发布时间】: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