【问题标题】:Variable does not pass to the view from the controller变量不会从控制器传递到视图
【发布时间】:2015-10-01 15:24:22
【问题描述】:

我是 AngularJs 的新手,无法解决这样的问题。

我尝试以这种谦逊的方式更改范围内的变量。

.controller('AuthController',  function($scope,Auth) {
      $scope.submit = function() {
          Auth.login($scope.username,$scope.password, function(result){
              $scope.result = result   
          });
      }
        })

Auth 是一种向服务器发出 GET 请求并获得如下响应的服务:

{ 'status': 1,  'message': "User does not found!"}

但是我的变量没有在我的模板中刷新。当我把这个

$scope.result = { 'status': 1,  'message': "User does not found!"}

在 $scope.submit 函数之外。它工作正常。

这是我的路线。

$stateProvider
    .state('index', {
        url: "/",
        templateUrl: "/static/templates/_index.html",
    }) 

我的模板是。

<div class="alert" >{{ result.message }}</div>

谁能解释我做错了什么? 谢谢。

这是我的服务。

function login(username, password, callback) {
  return $http.post('/api/login/', {
    username: username, password: password
  }).success(callback);

}

插入后

Auth.login($scope.username,$scope.password, function(result){
$scope.result = result   
console.log($scope.result);  

我在我的萤火虫中看到正确的数据。

Object { status=1, message="未找到用户!"}

$scope.$apply(); - 给我错误:[$rootScope:inprog] http://errors.angularjs.org/1.4.0/$rootScope/inprog?p0=%24digest

【问题讨论】:

  • $scope.result = result;之后尝试$scope.$apply();
  • console.log(result)$scope.result = result 之前的回调中说什么?
  • 你是在哪里调用提交函数吗?
  • Auth.login() 是否返回一个承诺或什么?我们可以看看你的 Auth 服务吗?
  • 这是我的服务。 function login(username, password, callback) { return $http.post('/api/login/', { username: username, password: password }).success(callback); }

标签: angularjs controller scope


【解决方案1】:

问题是通过改变来解决的

$scope.result = result.data;

$scope.blabla = result.data;

在那之后,我的模板终于向我展示了 {{ blabla }} 变量。

Angular 没有达到我的预期 :-(

【讨论】:

    【解决方案2】:

    如果您的Auth.login() 返回一个promise,您可以使用它的then 函数来定义成功和错误处理程序,例如:

        Auth.login($scope.username, $scope.password)
            .then(function(result){// success handler
                $scope.result = result  
                $scope.$apply(); 
            },function(error){// error handler
                console.log(error);
        });
    

    但是,如果它进行了ajax 调用并且没有返回promise,您可以使用$q 服务自己返回一个promise。你可以这样做:

     var deferred = $.defer();
     deferred.resolve($.ajax({
    // Your ajax call
    })); 
    

    您可以使用return deferred.promise 返回承诺。

    注意:确保在 Auth 服务中注入 $q 服务。

    【讨论】:

      【解决方案3】:

      你确定Auth.login() 没有返回承诺吗?看起来它想要,在这种情况下尝试......

      Auth.login($scope.username, $scope.password)
          .then(function(result){
              $scope.result = result   
          });
      

      没有看到您的身份验证服务很难说。

      【讨论】:

        猜你喜欢
        • 2019-08-21
        • 2012-02-10
        • 2017-05-14
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多