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?