更改控制器剂量中的$ scope值未在视图中反映 [英] change $scope value in controller dose not reflect in view

查看:36
本文介绍了更改控制器剂量中的$ scope值未在视图中反映的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在我的网络应用中实现注册功能,现在,我可以将日期发布到服务器上,并获得用户数据的响应,我的逻辑是在收到服务器的响应后,我的应用程序进入app.loggedin状态,并且我使用ui-router进行了如下配置:

I try to implement register functionality in my web app, Right now I can post date to my sever and get response with user data, my logic is after get response from sever, my app go to app.loggedin state, and I configured using ui-router as follow:

    .state('app.loggedin',{
      url:'',
      views: {  
          'header@':{  // specify the view need to change
                  templateUrl:'header.html'
                      }  ,

           'content@':{  // specify the view need to change
                 templateUrl:'main.html'
                      }  

        }
    }),

我希望登录后导航栏显示用户的用户名,我在控制器中更新$ scope.user,我确实是这样的:

I want the nav bar to show user's username after logged in, I update $scope.user in my controller, and I did like this:

 $scope.user
      UserFactory.register(username,password,function(err,result){
                                  if (err) {
                                    // do something

                                  }


                                    $state.go('app.loggedin',{reload :true});
                                    $scope.user=result.user;
                                    console.log($scope.user);


                          });

和我的html:

    <ul class="nav navbar-nav  color-white navbar-right" ng-controller="UserController">
  <li ng-if="!user"><a ui-sref="app.signup"><span class="glyphicon glyphicon-user"></span> signup</a></li>
  <li ng-if="!user"><a ui-sref="app.login"><span class="glyphicon glyphicon-log-in"></span> login</a></li>
  <li ng-if="user">
    <a ui-sref="app.signup"> {{user.username}}</a>
  </li>

</ul>

控制台可以正确打印用户,但是scope.user在我的视图中未更新,它是否仍为null,因此无法显示用户的用户名.如果我将ng-if =!user"更改为ng-if ="user",则注册不会显示.这是怎么了,我已经被困在这里几个小时了,请帮忙.谢谢,也是操纵DOM的正确方法吗?我是Angular的新手,我看到有人使用Directive来操纵DOM,有任何建议吗?

the console can print the user correctly, but scope.user is not updated in my view, can it is still null, and so cannot show user's username. if I change ng-if="!user" to ng-if="user", the sign up does not show. what wrong is here, I have been stuck here for couple hours, Please help. Thanks, and also is it the right way to manipulate DOM? I am very new to Angular, and I see someone use Directive to manipulate DOM, any sugesstion?

添加:service('UserFactory',['SharedDataFactory','$ http','baseURL',函数(SharedDataFactory,$ http,baseURL){

add : service('UserFactory',['SharedDataFactory','$http','baseURL', function(SharedDataFactory,$http,baseURL){

            this.register = function(username,password,callback){
                $http.post(baseURL+'user/register',
                    {username:username,password:password}).then(
                    function(response){
                          callback(null,response.data);
                    },
                    function(response){
                    callback(response.data,null);
                    }
                    );               
            };     
    }])

推荐答案

我认为您的问题是,成功登录后,您将转换为另一种状态:

I think your problem is that on successful login you are transitioning to another state:

$state.go('app.loggedin',{reload :true});
$scope.user=result.user;
console.log($scope.user);

$ state.go 将加载一个新状态( reload:true 将强制它成为一个全新的状态,即使它与当前状态相同也是如此)).控制器和关联的作用域不会被重复使用,因此在状态转换后您将拥有一个全新的 UserController 实例,但是您的执行代码仍引用旧的(不久将被销毁) $ scope .

The $state.go will load a new state (reload:true will force it to be a brand new state even if it is the same as the current one). Controllers and associated scopes don't get re-used, so you will have a brand new UserController instance after the state transition, but your executing code still refers to the old (shortly to be destroyed) $scope.

解决方案是将用户详细信息下推到服务中,因为服务始终是单例.您已经有一项服务,因此您可以在其中存储详细信息.

The solution to this is to push the user details down into a service as services are always singletons. You already have a service, so you can store the details there.

因此在UserController中,类似:

So in UserController, something like:

$scope.user = UserFactory.user;

和UserFactory类似:

And UserFactory something like:

service('UserFactory',['SharedDataFactory','$http','baseURL',
     function(SharedDataFactory,$http,baseURL){
        var self = this;
        this.user = {};
        this.register = function(username,password){
            return $http.post(baseURL+'user/register',
                {username:username,password:password}).then(
                angular.copy(response.data, self.user);
                return self.user;
                });               
        };     
}])

请注意,该服务将更新用户对象,而不是替换它.这意味着更改的属性也将通过 $ scope.user 引用可见.另外,我将您的函数更改为返回承诺而不是使用回调,因为这将简化对响应的进一步处理.

Note the service updates the user object rather than replacing it. This means the changed attributes will be visible through the $scope.user reference as well. Also I changed your function to return a promise rather than using a callback as that will simplify further handling of the response.

然后,您可以只从注册控制器调用注册功能:

Then you can just call the registration function from the register controller:

  UserFactory.register(username,password)
  .catch(function(err){
      // do something
  })
  .then(function(user) {
       $state.go('app.loggedin',{reload :true});
       console.log('Logged in', user);
  });

这篇关于更改控制器剂量中的$ scope值未在视图中反映的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆