Using angular service to exchange data between controllers

I am trying to connect two different controllers to each other.

Controller 1

function WelcomeCtl($scope, emailService) { $scope.save=function(){ emailService.saveEmail('Hi'); } } WelcomeCtl.$inject = [$scope, emailService]; 

This controller is intended for transferring text from a text field (using ng-model = 'email) and placing text in a service (emailService) so that it can be used in the next ng-view (which is controlled by the next controller) // for testing purposes, I just put hello right in the saveEmail function

Controller 2

 function SignupCtl($scope, emailService) { window.alert(emailService.getEmail()) } SignupCtl.$inject = [$scope, emailService]; 

For testing, I use 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 indicated in this service, window.alert displays "initial value" instead of "Hi

When I add more window.alert functions to the code to see what happens, I see that when save () is called, controller 1 executes and stores the value in the service, and express.js loads the next page. Then Controller2 is activated. When controller 2 activates, it reinitializes the service, returning the text to the "start value" value. Then, when getEmail is called, returns the value "initial value"

This bothers me because I have the impression that services are not initialized every time they are included in the controller.

Consulted resources.
Improved design for transferring data to other ng-views and saving them through controllers

I am also working on angular -express-seed https://github.com/btford/angular-express-seed

+6
source share
2 answers

Angular.js only works and saves data on one page. If your page reloads (as you seem to indicate when you say β€œexpress.js loads the next page”, then it reinitialized everything.

You must either:

+8
source

https://www.youtube.com/watch?v=HXpHV5gWgyk#t=29

this guy explained it in a very simple way.

0
source

All Articles