I am using $routeProvider
to route all of my apps pages to the correlating controllers
, but when two routes
use the same controllers
(i.e. /blog & /blog:id) how can I initialize a separate function
depending on the current route
.
So if the route is /blog I want to initialize $scope.loadPosts() on route load. If the route is /blog:id I want to initialize $scope.loadPost($id) on route load.
You could do a few things here, but my suggestion would be to pass the initialization function through the resolve of the route. You could do something like this:
angular.module('test', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/blog', {
controller: 'BlogController',
template: '<h1>Blog</h1>',
resolve: {
init: function() {
return function() {
console.log('Loading Blog');
}
}
}
})
.when('/blog/:id', {
controller: 'BlogController',
template: '<h1>Blog ID</h1>',
resolve: {
init: function() {
return function($route) {
console.log('Loading Blog Article ' + $route.current.params.id);
}
}
}
});
}
])
.controller('BlogController', ['$scope', '$route', 'init',
function($scope, $route, init) {
init($route);
}
]);
<!DOCTYPE html>
<html ng-app="test">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.6/angular-route.js"></script>
</head>
<body>
<a href="#/blog">Go to Blog</a>
<a href="#/blog/2">Go to Article 2</a>
<div ng-view></div>
</body>
</html>
Some other options would be:
Hopefully this code gets you started on the right track with whatever you decide.
edit Here's a link to a plunker, the code snippet appears to be acting oddly intermittently
The Simple way to do this is, using ng-init
in corresponding template
.
angular.module('demo', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/linkOne', {
controller: 'LinkController',
template: '<h1 ng-init="functionOne()">Hello world</h1>'
})
.when('/linkTwo', {
controller: 'LinkController',
template: '<h1 ng-init="functionTwo()">Hello Stackoverflow</h1>'
});
}])
.controller('LinkController', ['$scope', function($scope) {
$scope.functionOne = function(){
console.log("Hello");
}
$scope.functionTwo = function(){
console.log("Hello world");
}
}]);
HTML code:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.6/angular-route.js"></script>
</head>
<body>
<a href="#linkOne">Link One</a>
<a href="#linkTwo">Link Two</a>
<div ng-view></div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With