1
Starting from the idea that services are singletons (All Services are singletons), if I create a simple service with "local" variables and modify this in a controller, when accessing this value in another controller, it should keep the value, right?
Example:
angular.module("app", []);
angular.module("app").service("service", function() {
var _count = 0;
this.incrementCount = function() {
_count ++;
console.log(_count);
};
});
angular.module("app").controller("ctrl1", function($scope, service) {
$scope.increment = function() {
service.incrementCount();
}
});
angular.module("app").controller("ctrl2", function($scope, service) {
$scope.increment = function() {
service.incrementCount();
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="ctrl1">
<button ng-click="increment()" value="ctrl1" >Ctrl1 </button>
</div>
<div ng-controller="ctrl2">
<button ng-click="increment()" > Ctrl2 </button>
</div>
</body>
</html>
In this example, if you analyze the console, it increases the correct value regardless of the controller that is, but in my case, it turns out that I only have a controller on the page and when I go to the next page (without keeping the template), this value restarts at 0.
The way I make the system go to another page is by using the object window: window.location.href = "views/player.html"
I do so because my application runs on FILE protocol and I could not, at least, do otherwise, which prevents me from using templates (at least I could not use them).
That’s just the expected behavior?
With going to the next page without keeping the template, what do you mean? It’s a redirect through Angular using $Location?
– Ricardo Rodrigues de Faria
I just edited when I saw that this information was missing. It’s using the window object. For some reason, I couldn’t get him to go to another page using the $Location file protocol
– Paulo Gustavo