I am using angularjs in my application, all works well but before loading the template I just want to check that it actually exists on its given path.
Here is my code :
.when("/:page", angularAMD.route({
templateUrl: function (rp) {
return 'public/templates/' + rp.page.replace('.html', '') + '.php'; },
resolve: {
load: ['$q', '$rootScope', '$location',
function ($q, $rootScope, $location) {
var path = $location.path();
//console.log(path);
var parsePath = path.split("/");
var controllerName = parsePath[1];
controllerName = controllerName.replace('.html', '').replace('_', '');
var loadController = "public/js/controllers/" +
controllerName + "Controller.js";
var deferred = $q.defer();
require([loadController], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
}))
I want that before doing this return 'public/templates/' + rp.page.replace('.html', '') + '.php'; }
it must check if this file exists, otherwise I want to redirect to 404 page.
what now happens is, when I visits some invalid link, I dont get 404 status, instead it loads the main index.html file, and for that reason, it starts running the same code in an infinite loop, at last browser hangs.
Appreciate your help, thanks.
In ngRoute, you need to configure the routes in the config
block, and inside config block you can't use factories and services,
so you can use a simple trick to check if template exists, and if not return your 404 page.
var checkTplUrl = function(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return (http.status !== 404) ? url : './404.html';
};
.when("/:page", angularAMD.route({
templateUrl: function (rp) {
return checkTplUrl('public/templates/' + rp.page.replace('.html', '') + '.php'); },
resolve: {
load: ['$q', '$rootScope', '$location',
function ($q, $rootScope, $location) {
var path = $location.path();
//console.log(path);
var parsePath = path.split("/");
var controllerName = parsePath[1];
controllerName = controllerName.replace('.html', '').replace('_', '');
var loadController = "public/js/controllers/" +
controllerName + "Controller.js";
var deferred = $q.defer();
require([loadController], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
}))
Working example: https://plnkr.co/edit/1UjlFgT7dazMZOrAhZzY?p=info
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