Part of the route is like this
.when('/id/:id',
{
templateUrl: 'id.html',
controller: myController,
})
I want to validate if ':id' is from a set of ids, which is from a service functional call. If not, the page rendering should be prevented.
I got this part working by adding resolve in the route. The code is like this
.when('/id/:id',
{
templateUrl: 'id.html',
controller: myController,
resolve: {
validate: function($q, $route, myService) {
myService.getProjects().then(function(data) {
var defer = $q.defer(),
project = $route.current.params.project;
if (myContains(data.projects, project)) {
defer.resolve();
} else {
defer.reject({authenticated: false});
}
return defer.promise;
});
}
}
})
However when the promise is rejected, it does not fire up $routeChangeError, which I wrote like this
myApp.app.module.config(['$routeProvider', myApp.app.config])
.run(
['$rootScope', '$location', function($rootScope, $location) {
$rootScope.$on('$routeChangeError',
function(event, current, previous, rejection) {
var rejection = {};
if (!rejection.authenticated) {
$location.path('/').replace();
}
});
}]);
====update=== I got it working. The mistake I made earlier was to have 'return defer.promise' inside of then block.
If you already have the list of ids ,the this is how you can do,
.when('/id/:id', {
templateUrl: 'id.html',
controller: myController,
resolve: {
validateid: ["$q", "$routeParams", function($q, $routeParams) {
var id = Enumerable.From(arrayofids)
.Where(function(x) {
return x.id == $routeParams.id
});
if (id) {
return $q.when($routeParams.id);
} else {
return $q.reject({
authenticated: false
});
}
}],
}
}
resolve is a place where you can do all sort of action before navigation take place,
i had used linq.js which make all sort of iteration quite easily,i recommend you to just use it for once,you will love it