Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - Using angular service to share data between controllers

I am trying to have two different controllers communicate with each other.

Controller 1

function WelcomeCtl($scope, emailService) {
    $scope.save=function(){
        emailService.saveEmail(‘Hi’);
        }
}

WelcomeCtl.$inject = [$scope, emailService];

This controller is designed to take the text from a text field (with ng-model = ‘email’) and put the text into a service (emailService) so it can be used in the next ng-view (which is controlled by the next controller) //for testing purposes I am just putting ‘Hi’ directly into the saveEmail function

Controller 2

function SignupCtl($scope, emailService) {                                           
    window.alert(emailService.getEmail())
}

SignupCtl.$inject = [$scope, emailService];

For testing purposed I am using window.alert to display the value of getEmail()

emailService

angular.module('myApp.services', [])
       .service('emailService', function (){
           var text =”start value”;
           return{
               saveEmail:function (data){
                  text  = data;

              },
              getEmail:function (){
                  return text;
              }
          };
      });

As a result of using Controller1 and Controller 2 as specified with this service, window.alert prints out “start value” instead of ‘Hi’

When I put more window.alert functions in the code to see what is happening I see that when save() is called, Controller 1 executes and saves a value into the service and express.js loads the next page. Then Controller2 activates. When Controller 2 activates it reinitializes the service, setting text back to “start value”. Then when getEmail is called it return the value “start value”

This confuses me because I was under the impression that services were not initialized every time the were included in a controller.

Consulted resources.
Better design for passing data to other ng-view's and persisting it across controllers

I am also working off of the angular-express-seed https://github.com/btford/angular-express-seed

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Angular.js only works and keeps data on a single page. If your page reloads (as you seem to indicate when you say "express.js loads the next page", then it reinitialized everything.

You should either:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...