无法访问html中的$scope值,在$http中设置的值.成功后函数

Not able to access the $scope value in html, value set in $http.post success function

本文关键字:设置 函数 成功 http 访问 html 中的 scope      更新时间:2023-09-26

我无法访问$http post成功时设置的$scope属性的值。我试图访问它在index.html文件。下面是代码参考,请帮我解决一下,我是AngularJs新手

var app = angular.module('formExample', []);
app.controller("formCtrl", ['$scope','$rootScope', '$http',    
function($scope,$rootScope, $http) {
    $scope.loginurl = 'loginsubmit.php';        
    $scope.loginFormSubmit  = function(isValid) {           
        if (isValid) {              
            $http.post($scope.loginurl, {"username": $scope.username,"password": $scope.password}).
                    success(function(data, status) {
                        $scope.status = status;
                        $scope.data = data;
                        $scope.isAdmin=data.isAdmin;
                        $scope.username=data.username;                          
                        location.href="Index.html";                         
                    })  
        }else{
              alert('Form is not valid');
        }
    }

 html form code
 <div class="row" ng-app="formExample" >
       <div ng-controller="formCtrl">
          <div class"col-md-8">&nbsp;</div>
          <div>username: {{$scope.username}} </div>

对于登录和身份验证,我通常做与Marco相同的事情(在他的评论中提到),并将用户信息存储在$rootScope中。然而,这基本上是我使用它的唯一原因,因为它最好避免用一堆东西污染rootScope。

我在一个小游乐场里为你无耻地偷了这篇文章:

http://www.dotnet-tricks.com/Tutorial/angularjs/UVDE100914-Understanding-AngularJS- rootScope-and - scope.html美元

http://jsfiddle.net/chrislewispac/kd8v6thm/

var app = angular.module('myApp', []);
 app.controller('Ctrl1', function ($scope, $rootScope) {
 $scope.msg = 'World';
 $rootScope.name = 'AngularJS';
 });
 app.controller('Ctrl2', function ($scope, $rootScope) {
 $scope.msg = 'Dot Net Tricks';
 $scope.myName = $rootScope.name;
 });

所有其他答案/评论都很棒。我只是想让你拿着这把小提琴玩玩。通过隔离小问题,测试它们,打破它们,并在摆弄中修复它们,我学到了很多东西。

编辑:在Angular中有很多方法可以跨控制器共享数据:

另外,为了解决在没有数据库的情况下控制器之间共享数据的其他方法,你也可以创建一个auth 'factory。服务和工厂是跨控制器共享数据的好方法,我相信它们是真正想要的方式。

关于这个选项(和其他选项)的一个很好的讨论是:https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

参见更新后的fiddle with example of a service:

http://jsfiddle.net/chrislewispac/kd8v6thm/1/

加上以下内容:

app.service("auth", [ function () {
return {
    getAuth: function () {
        var info = {
            name: "Name",
            password: "Password"
            }
        return info;
        }
    };
}]);

您可能想要超时您的location.href,以便$作用域不会丢失。

在重定向之前,你有几个选项可以让你的用户数据全局化。你可以把你的用户变量放在一个影响所有视图的控制器中(比如app.js中的控制器),或者把它放在$rootScope或localStorage/sessionStorage中,就像评论中的@Marco建议的那样。

另外,用{{ username }}代替{{ $scope.username }}。后者不打印任何内容。