Here is the typical routing I use for my AngularJS apps.
$routeProvider
.when("/app/customer/:customerid/:departmentid", {
templateUrl: "/app/customer/customer.html",
controller: "customer",
controllerAs: "vm",
caseInsensitiveMatch: true,
resolve: ['customerService', function (customerService) {
return customerService.resolve();
}]
})
As you see in addition to the regular routing attributes, I
also used additional attributes such as controllerAs, resolve etc. Here is the
step by step dissection of my routing configuration
.when("/app/customer/:customerid/:departmentid", {
As all of you know, with the above statement I am defining a
routing which takes customerid and departmentid as query parameters
templateUrl: "/app/customer/customer.html",
controller: "customer",
With these above two statements I am defining the
templateUrl and controller for my routing.
controllerAs: "vm",
I like the controllerAs feature. It eliminates the need of
using $scope in my code and make my code clean.
caseInsensitiveMatch: true,
As the name suggests, Angular performs a case insensitive
matching while looking at the url for routing. This is important if are using a
combination of server (like asp.net) and client routing
resolve: ['customerService', function (customerService) {
return customerService.resolve();
}]
This is one of the important features of my routing. I don’t
want to burden my compiler with fetching the data from server and activities
other than rendering. As these are model or domain specific, I create a service
for each controller to handle these activities. As you know in most scenarios
you need to fetch data from the server before rendering the page, “resolve” is
designed for that activity. Until resolve returns (fetches the data or any
other activity) Angular waits and will not render the page. Resolve option also
helps avoiding the FOUC. Please see my
blog on this for further details
As you see with my routing configuration, I am able to
handle the preprocessing and also reduce the dependency of global $scope
variable.
asd
ReplyDelete