javascript - How do you set controller scope from the result of a signalr request? -
i have simple signalr hub created started within angularjs service called hubservice. able inject hubservice controller successfully. however, when call hub method returns data correctly. not able set $scope within controller signalr method callback.
/// <reference path="../typings/angularjs/angular.d.ts" /> // application. var app = angular.module("app", []); app.service("hubservice", function () { this.notification = $.connection.notificationhub; $.connection.hub.start(); }); // controller manages part of application. app.controller("mycontroller", function ($scope,hubservice) { $scope.message = ""; $scope.messageoutput = ""; hubservice.notification.client.addnewmessagetopage = function(message) { this.messageoutput = message; // fails. } $scope.dosomething = function () { hubservice.notification.server.send($scope.message); } });
the ui code simple , follows:
<div ng-controller="mycontroller"> <input type="text" ng-model="message" /> <button ng-click="dosomething()">do something</button> {{ messageoutput }} </div>
what best way update scope correctly within signalr callback?
if change following code signalr callback can results.
hubservice.notification.client.addnewmessagetopage = function(message) { this.messageoutput = message; // works this.$apply(); // if don't have still broken. }.bind($scope); ...
this not ideal because seems of hack.
using $apply()
not hack.
when updating scope events or code outside of angular context necessary tell angular in order run digests update view.
it may better use $timeout
(which calls $apply()
internally) not run conflicts digest in progress. pushes call end of active digest cycle
Comments
Post a Comment