我无法获得$ scope。$适用于AngularJS的工作

时间:2015-06-23 13:25:56

标签: javascript asp.net angularjs

我似乎无法获得$ scope。$ watch()在AngularJS中工作。我试图“观察”服务中包含的变量。该变量由一个控制器设置,我想在另一个服务器中对该变量进行操作。我真的很感激任何关于我做错的建议。这是我的代码: (注意:在Index.cshtml代码中,如果我从div中删除“data-ng-show”条件,则会显示div。所以我知道错误与data-ng-show有关=“loggedIn”条件。)

//In services.js file:
function Session() {
    this.loggedIn = false;
    this.updateLogIn = function (value) {
        this.loggedIn = value;
    }
}
angular.module('app.services', []).service('session', [Session]);
angular.module('app.controllers', [])
.controller('HomeCtrl', ['$scope', 'session', function ($scope, session) {
    $scope.loggedIn = session.loggedIn;

    $scope.$watch(
        function () {
            session.loggedIn;
        },
        function (newVal, oldVal) {
            if (newVal != undefined) {
                $scope.loggedIn = newVal;
            }
        },
        true
    );
}])
.controller('LoginCtrl', ['$scope', 'session', function ($scope, session) {
    $scope.loggedIn = session.loggedIn;
    $scope.login = function () {
        var s = "UserName=" + $scope.userName + "&Password=" + $scope.password;
        $.ajax({
            type: "POST",
            url: "http://localhost:50227/api/Authentication",
            data: s
        })
        .fail(function () {
            session.updateLogIn(false);
        })
        .done(function (data) {
            var tmp = JSON.parse(data);
            // do stuff with sessionStorage...
            session.updateLogIn(true);
        })
        .always(function () {
            $scope.loggedIn = session.loggedIn;
            $scope.$apply();
        })
    };
    $scope.logout = function () {
        session.updateLogIn(false);
        $scope.loggedIn = false;
    }
}])
//In Login.cshtml file:
<form id="frmLogin" class="form-inline search-box" data-ng-controller="LoginCtrl" ng-submit="login(userName, password)">
<div data-ng-hide="loggedIn">
    <input id="UserName" ng-model="userName" type="text" placeholder="Username or Email" required autofocus />
    <input id="Password" ng-model="password" type="password" placeholder="Password" required />
    <button type="submit" ng-disabled="!(userName && password)" disabled>Sign In</button>
</div>
<div data-ng-show="loggedIn">
    <a href="#" style="color:white;">Sign out</a>
</div>

//In Index.cshtml file:
<div data-ng-controller="HomeCtrl">
<div data-ng-show="loggedIn">
    <p>This should show when the user is logged in</p>
</div>

1 个答案:

答案 0 :(得分:3)

第一眼看到$ watch出现问题,该函数应该返回一个值!请在下次提供一名傻瓜!

    $scope.$watch(
    function () {
        return session.loggedIn;
    },