当设置为使用SignalR的服务器返回的值时,AngularJS表达式不会更新

时间:2016-05-12 08:38:45

标签: asp.net angularjs signalr

我有一个angularjs文件,它使用signalR连接到服务器。这是我的代码:

<div ng-app="myapp" ng-controller="myctr">

        //THE BELOW BUTTON SHOULD CHANGE THE VALUE OF {{testo}}
        <button ng-click="AggiornaTesto()">Cliccami</button>

        <input type="text" ng-model="input" />

        //THe EXPRESSION BELOW ONLY UPDATES IF I PRESS THE BUTTON "CLICCAMI" TWICE
        {{testo}}

        <br />
        Stato Connessione: {{statoconnessione}}
    </div>
    <script>
        var app = angular.module("myapp", []);
        app.controller("myctr", function ($scope) {
            $scope.testo = "";
            $scope.input = "";
            $scope.btnenabled = "true";
            $scope.statoconnessione = "";
            $.connection.myHub1.client.JSMet1 = function (x) {

                //THE FOLLOWING LINE IS EXECUTED CORRECTLY 
                //BECAUSE IN THE CONSOLE I CAN SEE IT IN THE CONSOLE, 
                //AND THE VALUE OF X IS CORRECT
                console.log("JSMet1 " + Math.random()+" "+x);

                //MAYBE ALSO THE FOLLOWING LINE IS EXECUTED BUT THE 
                //EXPRESSION {{testo}} IS UPDATED ONLY IF I PRESS THE BUTTON TWICE
                $scope.testo = x;
            };
            $scope.AggiornaTesto = function () {
                console.log("AggiornaTesto " + Math.random());
                $.connection.myHub1.server.cSMet1($scope.input);
            };
        });
        $.connection.hub.start().done(function () {
            $.connection.hub.stateChanged = function (stato) { $scope.statoconnessione = stato };
        });
    </script>

问题是表达式{{testo}}更新了一次是和一次没有。同时每按一次“cliccami”按钮就应该更新。链接到按钮的功能,即:

$.connection.myHub1.client.JSMet1 = function (x) {....}
每次按下按钮都会执行

,因为我已经检查了控制台并且执行了console.log功能。但下一行,即

$scope.testo = x;

似乎没有被执行,因为{{testo}}没有改变。

2 个答案:

答案 0 :(得分:0)

angularJS中有一个称为摘要循环的东西,可以在所有已知的角度指令上自动为您进行双向数据绑定。在您的情况下,您必须自己触发摘要周期,以便将{{testo}}更改为新值。为此,你必须致电$scope.$apply() 有关digest cycle的更多信息http://www.sitepoint.com/understanding-angulars-apply-digest/

答案 1 :(得分:0)

当您将角度代码与不知道角度的库混合时,这是一个常见问题。当您将回调函数传递给角度以外的东西时,您必须手动触发角度摘要循环。

最干净的方法是确保所有回调代码都在$scope.$apply()的调用中发生:

$.connection.myHub1.client.JSMet1 = function (x) {
    $scope.$apply(function() {
        console.log("JSMet1 " + Math.random()+" "+x);
        $scope.testo = x;
    })
});