简体   繁体   English

AngularJs不更新模型

[英]AngularJs not updating model

I'm trying to replace Knockout with Angular right now. 我正在尝试将淘汰赛替换为Angular。 However, there seems to be some quirks that I simply can not get around so far. 但是,似乎有些怪异之处我至今无法解决。

In the login function of my site, I do an ajax call and get some user information, this info is then set in the controller. 在我的网站的登录功能中,我进行了ajax调用并获取了一些用户信息,然后在控制器中设置了此信息。

like this: 像这样:

    $scope.login = function () {

        var data = {
            userName: $('#txtLoginName').val(),
            password: $('#txtLoginPassword').val(),
        };

        console.info(data);

        postJSON("/StrengthTracker/User/Login", data, function (result) {

            if (result.result == "ok") {
                $('#loginDialog').modal('hide');

       //setting controller variables <------------
                $scope.isLoggedIn = true;
                $scope.userId = result.userId;
                $scope.userName = result.userName;
                $scope.publicId = result.publicId;
                $scope.gender = result.gender;
                $scope.unitName = result.unit;

                console.info(result);

                notify("Welcome " + $scope.userName);
            }
            if (result.result == "fail") {
                notifyFail("Login failed");
            }
        });
    }

I can see that the correct data is returned, the notify(..) call does say "Welcome Roger" for example. 我可以看到返回了正确的数据,例如notify(..)调用确实显示“ Welcome Roger”。 so far so good. 到现在为止还挺好。 But it seems like Angular doesnt see that the variables have changed. 但似乎Angular看不到变量已更改。

If I do hit the login function again, THEN angular notices the changes and understands that the user is logged in. 如果我确实再次点击了登录功能,则THEN Angle会注意到所做的更改并了解用户已登录。

Ideas? 想法?

This has to do with AngularJS not being aware of your callback function, it's not tracked. 这与AngularJS没有意识到您的回调函数有关,因此没有被跟踪。 As Yoshi already suggested, using $scope.$apply fixes it because this forces AngularJS to become aware. 正如Yoshi已经建议的那样,使用$scope.$apply修复,因为这迫使AngularJS意识到这一点。

Note that AngularJS has built-in support for making AJAX-requests with $http and $resource (in case of REST services). 请注意,AngularJS内置支持使用$http$resource进行AJAX请求(对于REST服务)。 One of the advantages of using one of these objects is that you won't have to manually use $apply , another is that your code remains testable with the built-in support for unittests. 使用这些对象之一的优点之一是您不必手动使用$apply ,另一优点是,使用对单元测试的内置支持,您的代码仍然可以测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM