AngularJS Service Passing Data Between Controllers

后端 未结 1 1463
南笙
南笙 2020-11-29 22:01

When using an AngularJS service to try and pass data between two controllers, my second controller always receives undefined when trying to access data from the service. I a

相关标签:
1条回答
  • 2020-11-29 22:14

    Define your service like this

    app.service('userService', function() {
      this.userData = {yearSetCount: 0};
    
      this.user = function() {
            return this.userData;
      };
    
      this.setEmail = function(email) {
            this.userData.email = email;
      };
    
      this.getEmail = function() {
            return this.userData.email;
      };
    
      this.setSetCount = function(setCount) {
            this.userData.yearSetCount = setCount;
      };
    
      this.getSetCount = function() {
            return this.userData.yearSetCount;
      };
    });
    

    Check out Duncan's answer here:

    AngularJS - what are the major differences in the different ways to declare a service in angular?

    0 讨论(0)
提交回复
热议问题