Reputation: 975
Why the controller logic is executed only if you are in another view ?
http://jsfiddle.net/J5hRc/128/
If you press twice in a link, the alert is only showed the first time. I am doing something wrong ?
HTML:
<script type="text/ng-template" id="page1.html">
Page 1
</script>
<script type="text/ng-template" id="page2.html">
Page 2
</script>
<div>
<ul>
<li><a href="#/link1">Page 1</a></li>
<li><a href="#/link2">Page 2</a></li>
</ul>
<div ng-view></div>
</div>
Javascript:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl1', function($scope) {
alert('controller logic1'); });
myApp.controller('MyCtrl2', function($scope) {
alert('controller logic2'); });
myApp.config(function($routeProvider) {
$routeProvider
.when('/link1', {
controller: 'MyCtrl1',
templateUrl: 'page1.html'
})
.when('/link2', {
controller: 'MyCtrl2',
templateUrl: 'page2.html'
});
});
Upvotes: 1
Views: 41
Reputation: 17492
No. You're not doing anything wrong. This is the default behavior in the web and you browser makes sure it doesn't navigate to a link that you're already on, common sense if you think about it. You can reload the route if you manually navigate to it and call $route.reload()
(instead of using hrefs). For example:
$scope.goToRoute= function(url){
$location.path(url);
$route.reload();
}
Upvotes: 1
Reputation: 9597
Your alerts are in the constructor function of the controller. So, they are obviously only going to fire when the controller is created.
The controllers in your example are created when the route is changed, so that is why you see them fire the alert when you change to a new route. Once you're on a route, the controller won't be instantiated again unless you leave and come back.
If you want this logic to fire every time you click the link as well as when you first navigate to the view, then wire up a clickHandler and call the clickHandler in the constructor of the controller:
myApp.controller('MyCtrl1', function($scope) {
$scope.showAlert = function () {
alert('controller logic1');
}
$scope.showAlert();
});
And in your view:
<li><a ng-click="showAlert()" href="#/link1">Page 1</a></li>
Upvotes: 1
Reputation: 193301
Because if you are on the page1 with $location path /link1
, and then you click on the link /link1
location path does not change again of course, hence route won't change either. And because of that $routeChangeSuccess
event never occurs, which is being listened by ngView
directive. This ngView
directive internal event listener responsible for controller instantiating, which of course won't happen too.
Upvotes: 0