Why my $scope attributes keep resetting in my AngularJS application?

后端 未结 2 1127
悲&欢浪女
悲&欢浪女 2021-01-18 14:26

I have the following AngularJS application composed of a template (index.html), an app definition (app.js), a controller definition (controll

2条回答
  •  一整个雨季
    2021-01-18 14:50

    You should use services (or $rootScope) to store the information you want to persist. Services are singletons and you can inject them in the controllers, anything you set there will persist in your application.

    $scopes are deleted when you change the route so they won't persist.

    Here is an example:

    var myApp = angular.module('myApp',[]);
    myApp.factory('SomeService', function() {
      return {
          myAttribute : '12345'
      };
    });
    
    var MyController=['$scope','$http','$location', 'myService', 'SomeService',function ($scope, $http, $location, myService, SomeService) {
       //do some fancy stuff
       SomeService.myAttribute; //this is how you access myAttribute
    }];
    

    Also I'd create a function inside the service to fetch the values you want via AJAX (instead of having it inside you controller), so the service would be something like:

    myApp.factory('SomeService', function() {
    
        var SomeService = {};
    
        var myAttribute;
    
        SomeService.getMyAttribute = function () {
    
             if(!myAttribute) {
    
                //run ajax request then populate and return myAttribute
    
             }
             return myAttribute;
        };
        return SomeService;
    });
    

提交回复
热议问题