I have a simple single page app that shows images on it.
On first load the page is blank and people add their own images however if they then return to the page with their saved id in the url then I want the page to grab the previous model.
Now all my previous attempts to use routeProvider have failed unless I put ng-view somewhere in the page. But this then affects the scopes that are inside the ng-view scope.
Basically I need to respond differently on the page depending if there is an id in the url or not but I'm not changing the view and I need to get the id from the route parameters.
So I was just wondering how you guys would go about doing this as I seem to be barking up the wrong trees! Any help would be much appreciated.
Here's one way to handle url with and without id, using standard routeProvider setup, with one controller:
JS:
var app = angular.module('plunker', []);
app.config(function($routeProvider){
return $routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home.html'
})
.when('/:id', {
controller: 'HomeController',
templateUrl: 'home.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('HomeController',
[
'$scope',
'$routeParams',
function($scope, $routeParams) {
if($routeParams.id){
$scope.id = $routeParams.id;
// handle scenario when there is an id in URL
return;
}
// handle scenario when there is no id
$scope.id = 'no ID!!';
}
]
);
Plunker
And here's another way, without using ng-view and relying on $location service:
var app = angular.module('plunker', []);
app.config(
['$locationProvider',
function($locationProvider) {
$locationProvider.html5Mode(true);
}
]
);
app.controller('HomeController',
[
'$scope',
'$location',
function($scope, $location) {
$scope.$watch(function(){
return $location.hash();
},
function(id){
$scope.id = id;
}
);
$scope.$watch('id', function(id){
if(id){
// handle scenario when there's id available
return;
}
// handle scenario when there is no id
});
}
]
);
Plunker
This plunker initiates a $route service by adding $route
as a dependency in the app run block. The idea is described here.
angular.module('myApp', ['myApp.controllers'])
.config(function($routeProvider) {
return $routeProvider.when("/", {
controller: 'firstCtrl'
}).when("/numbers/:number", {
controller: 'secondCtrl'
});
}).run(function($route) {});
angular.module("myApp.controllers", [])
.controller("firstCtrl", function($scope) {
$scope.numbers = [1, 2, 3];
})
.controller("secondCtrl", function($scope,$routeParams, $rootScope, $location) {
return $rootScope.$on("$routeChangeSuccess", function(event, current) {
$scope.current_path = $location.$$path;
$scope.number = $routeParams['number'];
});
});
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