在角度js服务中观察并应用对象的更改

时间:2016-05-07 08:20:05

标签: javascript jquery angularjs angularjs-rootscope

我正在尝试更改并在角度js服务中应用对象的值。

我已经能够成功观看对象并且我看到了更改,但我无法将其应用于生效。

我正在更改登录控制器的值。

我正在观看$ rootScope.userobject,并希望立即对$ rootScope.userobj应用更改,因为它在我的服务中用于一些重要的东西,但它似乎并不适用。我究竟做错了什么 。看下面的代码

            MyApp.angular.factory('appService', function ($rootScope, $timeout) {

              $rootScope.userobject = localStorage.getItem('userdataconfig');
              $rootScope.userobj = JSON.parse($rootScope.userobject);

              if(!rootScope.userobj){
              $rootScope.userobj = {};
              }

              $rootScope.$watchCollection('userobject', function(newvalue, oldvalue)
            {
              $timeout(function(){

               $rootScope.userobject = newvalue;
               $rootScope.userobj = JSON.parse($rootScope.userobject);// i need this updated value to take effect so i can use it in my userconfig below

             });
            }, true);



            return {
                    userconfig: {token: $rootScope.userobj.token, id: $rootScope.userobj.id, username: "josieboy", fullname: $rootScope.userobj.name, profile_pix: ""}
                }

            })

            MyApp.angular.controller('loginctrl', ['appService', '$scope', '$http', 'InitService', '$rootScope', function (appService, $scope, $http, InitService, $rootScope) {
            $scope.loginnow = function()
            {
              var userdata = { 'id': 3, 'token':'867eb6fcd04b543f97ff6d2c0a64c557', 'name':'Ajose Joshua', 'profile_pix':''};
              localStorage.setItem('userdataconfig', JSON.stringify(userdata));
              var userobject = localStorage.getItem('userdataconfig');
              $rootScope.userobject = userdata;

              }

            }])

0 个答案:

没有答案