Sometime it’s needed to load data before loading view in
application. AngularJS has option to implement same in place of routing.
We can say to AngularJS that before redirect to view, let’s
complete the promise at first. Here is the implementation.
var app = angular.module('App', ['ngRoute']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/myroute', {
templateUrl: '../app/template.html',
controller: 'myController',
resolve: {
message: function (nameService) {
return
nameService.returnName();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
You can notice that, “myroute” routing entry has taken
resolve parameter which takes service as function argument. We will define the
service now. Here is the implementation of service.
app.service('nameService', function () {
this.returnName = function () {
return "Sourav Kayal";
};
});
Here is the controller which takes “message” as argument
which will return by “resolve” in routing section.
app.controller('myController', function ($scope, message) {
$scope.name = message;
});
And once we run the application, we will see the name has
returned to controller.
No comments:
Post a Comment