AngularJS数据绑定通过responsemessage无法按预期工作

时间:2017-01-19 12:31:51

标签: html angularjs data-binding websocket

代码如下

var myApp = angular.module("gameModule", []);

myApp.controller("gamecontroller", function ($scope) {
    $scope.message = "test";

    // websocket connection.
    var gameHub = $.connection.socketHub;

    $.connection.hub.start().done(function () {
        var clientid = $.connection.hub.id;

        $(function () {
            var user = { signalrsessionid: clientid };
            $.ajax({
                type: "POST",
                data: JSON.stringify(user),
                url: "http://localhost:53629/api/game/signalr",
                contentType: "application/json"

            }).done(function (response) {
                alert(response);
               $scope.responsemessage = response;
            });
        });
    });
});

和前端代码

<!DOCTYPE html>
<html ng-app="gameModule">
<head>
<title>game registration</title>
<meta charset="utf-8" />

<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.js"></script>
<script src="Scripts/angular.js"></script>
<!--Automatisch gegenereerde signalR hub script -->
<script src="signalr/hubs"></script>

<script src="Scripts/rouletteAngular.js"></script>

</head>
<body>
<div ng-controller="gamecontroller">
    {{ message }}
    {{ responsemessage }}
</div>

所以&#39;消息&#39;正在显示,带有响应的警报框显示正确的响应,但响应消息不显示任何值。

任何人都可以告诉我我做错了什么。

1 个答案:

答案 0 :(得分:0)

你必须调用$ scope。$ apply();或$ scope。$ digest();设置$ scope.responsemessage = response之后;因为你正在使用jQuery ajax调用,这是在Angulars上下文之外。

修改

这里你有很好的方法在AngularJS中使用SignalR: http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html