Reputation: 2221
Code in plunker. I have two controllers. In first controller i have handler for button in my view
$scope.click = function () {
$location.url("/some");
console.log("clicked");
}
In handler i change URL. I also configured my $routeProvider.
var app = angular.module('plunker', []).config( function ($routeProvider) {
$routeProvider.when('/some', {template: " counter is {{n}}</br> <button ng-click='click()'>click to load new url but still with \"loading cntl\"</button>", controller: "loading"})
.when("/second",{controller: "loading"});
});
Here i have two different routes that have the same controller - loading
controller
So after my URL was changed to /some
new button appears in my view. I have another handler for this button in loading
controller.
app.controller("loading", function ($scope,$location) {
$scope.n= $scope.n || 0;
console.log("at the begining n is "+ $scope.n);
$scope.click = function click() {
$scope.n++;
console.log("n after++ is " + $scope.n);
$location.url("/second");
}
});
Here i increment n
variable and change URL to /second
. In my $routeProvider
i indicated that route with this URL must have loading controller
as well. After triggering of the button it disappears because /second
router have no template. I press button on main view again, my loading controller
is executed once more, but the n
variable is still 0. Why the value of n
is not 1
?
I know that my explanation is confusing, but i have the code in plunker
Upvotes: 0
Views: 60
Reputation: 37711
You're instantiating a new controller that has a new scope (and thus a new variable n
). You need to keep the iteration data in something more persistant, like a parent scope, service, localStorage, etc (depends what you need the data for).
Here's a working example using $rootScope
, just so you can see (you should probably use something other than the $rootScope in your final code): http://plnkr.co/edit/HETROBPwa6VyjX83Eev0?p=preview
I added a simple console.log('scope', $scope);
in the controller, so you can see that each time you change the url, a new scope is created.
Upvotes: 1