AngularJS controller is executed every time the view is routed - javascript

Every time I change the path through a link like the following
<li>Home</li>
The controller for the view in the router definition gets run again.
config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
// $locationProvider.hashPrefix('!');
$routeProvider.when('/home', {
templateUrl: 'partials/home.html',
controller: 'mainCtrl'
});
$routeProvider.when('/test', {
templateUrl: 'partials/test.html',
controller: 'testCtrl'
});
$routeProvider.otherwise({
redirectTo: '/home'
});
}
]);
I don't think that this is default behavior (I found no mention of it in the documentation), however I can't see what the problem is.
P.S.
I don't have an ng-controller assigned to any DOM element in my templates since I've seen someone else with a similar issue where this was the problem.

It is a default behavior.
Basically controller is function used to argument Angular Scope. So it need to be called each time the page associated with the controller is opened. Each time your page is navigated angular will create new scope.

Related

ng-view - how to disable re-init of pages

I'm writing an angularjs 1.5.0-rc0 application with angular-route.
Each page in the view is related to another, which means in one tab I start a process, and in another tab I go to view the statistics of the process.
the problem that I'm having is that once I switch tabs, the controller is re-initializing the data and everything is reset.
my ng-view is configured with the following code:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/index.html',
controller: 'IndexController',
controllerAs: 'index'
})
.when('/update-flows-rarities',{
templateUrl: 'templates/update-flows-rarities.html',
controller: 'UpdateFlowsRaritiesController',
controllerAs: 'updateFlowsRarities'
})
.when('/run-flow',{
templateUrl: 'templates/run-flow.html',
controller: 'RunFlowController',
controllerAs: 'runFlow'
})
.when('/system-stats',{
templateUrl: 'templates/system-stats.html',
controller: 'SystemStatsController',
controllerAs:'systemStats'
})
.otherwise({redirectTo: '/'});
});
I don't have any other relevant code to paste since it's a generic question, any information regarding the issue would be greatly appreciated.
In AngularJS, services are instantiated as singleton, So you can store data in them and access that data from your controllers.

Need to pass $scope with variables to another page in angular?

I have this routes:
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/next', {
templateUrl: 'views/next.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.otherwise({
redirectTo: '/'
});
When I'm in main page. I clicking to next button and see 'views/next.html'. But I'm not have my previously $scope. How I can get this scope?
New route renders new template and also bind new scope to template. So you can't really just use the same scope for both routes. However, there are at least two workarounds.
1). $rootScope. $rootScope is available in all views so you can store some data in it and be able to access it in any template.
2). Service. Use shared service in both controllers. This is probably optimal solution for most cases.

Stop Controller's activity when switch route

I create single page app by AngularJS and I found my problem. I have function refresh data every 2 minutes by jQuery in route A. When I change to other route, that function in controller is still working. This is my code.
App.js
var newsapp = angular.module('newsAppMD', ['ngRoute']);
newsapp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/news', {
templateUrl: 'templates/news.html',
controller: 'imageNewsCtrl'
}).
when('/news/:nameCat', {
templateUrl: 'templates/news-thumbnail.html',
controller: 'newsPageCtrl'
}).
otherwise({
redirectTo: '/news'
});
}]);
newsapp.controller('imageNewsCtrl', function($scope, $http, $interval, $timeout ) {
$('#bottom-bar').find('#epg').hide();
$scope.updateTimeEPG = 120000;
$scope.fetchFeed = function() {
$http.get("http://wi.th/thaipbs_tv_backend/epg_forJS.php").success(function(response) {
$scope.items = response.Schedule;
console.log($scope.items);
$timeout(function() { $scope.fetchFeed(); }, $scope.updateTimeEPG);
}).then(function() {
$('#bottom-bar').find('.loading').hide();
$('#bottom-bar').find('#epg').show();
});
};
$scope.fetchFeed();
});
newsapp.controller('newsPageCtrl', function($scope, $http, $location) {
// blah blah blah
}]);
I choose /news imageNewsCtrl work. And when I switch to other route, function in imageNewsCtrl still work (I see function print console.log when I changed route). I want to stop function in controller when change route. Thanks for your suggestion everyone. :)
I am not too entirely sure, but try using $stateProvider instead of $routeProvider. If you do, then you need to npm install angular-ui-router (it is a powerful third party module) and replace ngroute. I only user $routeProvider for the .otherwise function. You can also do a lot more cool stuff like onEnter and onExit with $stateProvider. Another thing is I would recommend you to use only Angular instead of jQuery. I do not really see a point of you using both. Use Angular's two-way data binding! Also, if you really want to get into Angular, then I recommend John Papa's style guide. This guys knows what he is talking about for making a great Angular app. I hope this info helps!

Can't fix the hashtag in my angularjs app path

I know you guys are going to say "It's duplicated" but it doesn't work for me.
I'm doing exactly the same thing and here's what happens.
This is my config code:
portfolioApp.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
controller: 'portfolioController',
templateUrl: 'partials/home.htm'
})
.otherwise({redirectTo: '/home'});
if(window.history && window.history.pushState){
$locationProvider.html5Mode(true);
}
});
The URL without the locationProvider and setting path to "/" instead of "/home" would be:
http://localhost:8080/portfolio/#/
Okey, i would like to remove the hashtag and the "portfolio" path so that way it would be:
http://localhost:8080/home
With the config i've posted, it does it (the first time i refresh). But what happens? happens that if I refresh the page again with the new path... i get a 404 Tomcat Error.
In the first refresh when i write localhost:8080/portfolio and the path gets converted into "/home", I get in the console an error saying that the "partials/home.htm" can't be found 404.
So either way, it can't read my partial, and then when I refresh everything is broken.
How can I solve this? what am I doing wrong?
Make sure your including these to scripts in the header of your HTML document Where you are implementing your module. The two provided below are for implementing the most current version of angular as well as the most current version of the angular route script:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular-route.js"></script>
Make sure your injecting ngRoute into your module, here's an example of mine:
angular.module('controller', ['ngRoute','ngResource', 'ngCookies', 'ngSanitize'])
Here is an example of my config block, make sure you inject both routeProvider and locationProvider:
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: '../partials/member.php',
controller: 'Member',
access: 'member'
})
.when('/leaderboard', {
templateUrl: '../partials/leaderboard.html',
controller: 'Leaderboard',
access: 'member'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}])
If your doing all of this and it still doesn't work post a plunker of your code. Thanks.

AngularJs reload page instead only load view

I have a simple app in AgularJS. I need to load view in route
$routeProvider.when('/articles/:url', {
templateUrl: 'partials/article.html',
controller: ArticleCtrl
});
But if i click on
Page reloads and after reload Angular try to load partials/article.html view, but fails on error "NetworkError: 404 Not Found - http://localhost:3000/clanky/partials/article.html"
I know that I can use "../partials/article.html" insted "partials/article.html", but I mean that isn't the core of problem.
There are my routes:
blog.config([
'$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
templateUrl: 'partials/main.html',
controller: MainCtrl
});
$routeProvider.when('/login', {
templateUrl: 'partials/login.html',
controller: LoginCtrl
});
$routeProvider.when('/backend', {
templateUrl: 'partials/backend.html',
controller: BackendCtrl
});
$routeProvider.when('/articles/:url', {
templateUrl: 'partials/article.html',
controller: ArticleCtrl
});
return $routeProvider.otherwise({
redirectTo: '/'
});
}
]);
P.S.
If I try go to the any other route, for example, login, it partialy works, but reload is still here.
Thanks for yours answers
seems that I've got the same problem as you.
I don't know how to handle this but I think that's because the page was reloaded.
When you are not setting the html5Mode to true, then will be # at the url, and if you reload the page, the # will track the information to the $scope to work with the htmlHistory api so that the app can work properly even with the page refresh.
But once you set the html5Mode to true, then there's no # to store any $scope information, and when the page reload, angular can not found the accordingly scope so it return 404.
You can check $location section on angularjs guide, it has a section explaining why this happen.
Page reload navigation
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.
Hope this can be helpful for you, and if you got any better answer, please let me know, I'm also waiting for the right way to solve it.
Start your templateUrl with a slash:
templateUrl: '/partials/article.html'
instead of
templateUrl: 'partials/article.html'

Categories