Updating a service variable in one controller and using the updated value in another controller - Angular JS

I defined a service called NameService in my controller.js . I want to use the variable present in the NameService in two different controllers.

My service is as follows

 App.service('NameService', function(){ this.Name = ""; this.getName = function(){ return this.Name; }; this.setName = function(name){ this.Name = name; } }); 

I have a controller called netController in which I update the value of the Name variable found in my NameService . I want to use the updated value in my page1Controller .

netController as follows:

 App.controller('netController', ['$scope','$http','$window','NameService', function($scope,$http,$window,NameService) { $scope.initNet = function() { $http.post('/initNet',$scope.network).success(function(response) { if(response.status == "true") { $scope.$watch('NameService.setName()', function(){ NameService.Name = $scope.network.name; }); NameService.setName($scope.network.name); $window.location.href = '/page1'; } else { $scope.error = "Error!"; } }); } }]); 

If I do console.log(NameService.netName); in my netController , it prints the updated value.

page1Controller as follows

  App.controller('page1Controller', ['$scope', '$http','NameService', function($scope, $http,NameService) { console.log(NameService.Name); }]); 

When do console.log(NameService.name); in my page1Controller , it gives an empty string.

Can someone please help me fix this?

+5
source share
2 answers

use factory instead of service

 gisApp.factory('NameService', function () { var _name = ""; return { getName: function () { return _name; }, setName: function (name) { _name = name; } } }); 
0
source

because when you invoke this variable to print, it is not defined yet. $ http , and it takes some time . Have you tried setting the interval inside page1Controller ? as

 App.controller('page1Controller', ['$scope', '$http','NameService', '$timeout' function($scope, $http,NameService, $timeout) { $timeout(function(){ console.log(NameService.name) },2000); ... 

Edited

Then try something like this

 gisApp.service('NameService', function(){ return { Name: '', getName: function(){ return this.Name; }, setName: function(name){ this.Name = name; } }); 

because the syntax you are using, you must create an instance of this service using " new " in order to use it as a class.

0
source

All Articles