I configure my app in the following run block. Basically I want to preform an action that requires me to know the $routeParams every $locationChangeSuccess.
However $routeParams is empty at this point! Are there any work rounds? What's going on?
app.run(['$routeParams', function ($routeParams) {
$rootScope.$on("$locationChangeSuccess", function () {
console.log($routeParams);
});
}]);
UPDATE
function configureApp(app, user) {
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/rentroll', {
templateUrl: 'rent-roll/rent-roll.html',
controller: 'pwRentRollCtrl'
}).
when('/bill', {
templateUrl: 'bill/bill/bill.html',
controller: 'pwBillCtrl'
}).
when('/fileroom', {
templateUrl: 'file-room/file-room/file-room.html',
controller: 'pwFileRoomCtrl'
}).
when('/estate-creator', {
templateUrl: 'estate/creator.html'
}).
when('/estate-manager', {
templateUrl: 'estate/manager.html',
controller: 'pwEstateManagerCtrl'
}).
when('/welcomepage', {
templateURL: 'welcome-page/welcome-page.html',
controller: 'welcomePageCtrl'
}).
otherwise({
redirectTo: '/welcomepage'
});
}]);
app.run(['$rootScope', '$routeParams', 'pwCurrentEstate','pwToolbar', function ($rootScope, $routeParams, pwCurrentEstate, pwToolbar) {
$rootScope.user = user;
$rootScope.$on("$locationChangeSuccess", function () {
pwToolbar.reset();
console.log($routeParams);
});
}]);
}
Accessing URL:
http://localhost:8080/landlord/#/rentroll?landlord-account-id=ahlwcm9wZXJ0eS1tYW5hZ2VtZW50LXN1aXRlchwLEg9MYW5kbG9yZEFjY291bnQYgICAgICAgAoM&billing-month=2014-06
this worked for me, inside your run callback:
.run(function($rootScope, $routeParams, $location) {
$rootScope.$on("$locationChangeSuccess", function() {
var params = $location.search();
console.log(params);
console.log('landlord-account-id:', params['landlord-account-id']);
console.log('billing-month', params['billing-month']);
});
})
By accessing /rentroll you will get empty $routeParams because your $routeProvider
configuration for that path is not expecting any variable on URL.
$routeParams is used for getting variable value of your URL. For example :
$routeProvider
.when('/rentroll/:variable', {...});
and access it on /rentroll/something will give you $routeParams as below :
$routeParams.variable == 'something';
https://docs.angularjs.org/api/ngRoute/service/$routeParams
Explains a bit about when the $routeParams are available and why.
To solution here might be to use $route.current.params
Related
I have just started learning angularJS but i can notice the same thing so many time that at some places when we start writing a function in angularJS i noticed that some people define the function they are going to use like this
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
}]);
But the same function is working fine if we just write the function without this ['$routeProvider' like this
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(function($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
});
I know there is no big difference when coming to code writing but still is there any difference in both the ways. If yes, then is it about minifying? and is there any negative point other that that of using it?
Thanks in advance!
mainApp.config(['$routeProvider', function($routeProvider) {
}]);
This type define a controller is callled Inline Array Annotation. And It is min-safe. min-safe mean if you minify your code then it will still work.
mainApp.config(function($routeProvider) {
});
This type of define a controller is called 'Implicit Annotation'. And its not min-safe. min-safe mean if you minify your code then it will not work.
And there a another way to declare a controller $inject Property Annotation
var MyController = function($scope, greeter) {
// ...
}
MyController.$inject = ['$scope', 'greeter'];
someModule.controller('MyController', MyController);
read more info click here
I'm using routeProvider to set the controller and a route param when my application is configured. Here's the code that I'm using:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/person/:uuid/report', { controller: 'CandidateCtrl' }).
when('/person/:uuid/confirm', { controller: 'ConfirmCtrl', }).
when('/person/add', { controller: 'AddCtrl' })
}]);
However, the controller is not being set correctly. Additionally, when I set the controller with ng-controller in the page itself, the routeParams object is empty. What am I doing wrong?
Edit:
I've also tried this, which also isn't associating the controller with the page nor setting the route-params.
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/person/:uuid/report', { controller: 'CandidateCtrl', template: 'templates/report.html' }).
when('/person/:uuid/confirm', { controller: 'ConfirmCtrl', template: 'templates/confirm.html' }).
when('/person/add', { controller: 'AddCtrl', template: 'templates/add.html' })
}]);
Here's the controller that I'm testing this out with:
appController.controller('CandidateCtrl', ['$routeParams',
function($routeParams) {
console.log($routeParams);
}]);
Try to add templateUrl
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/person/:uuid/report', {
templateUrl: 'partials/CandidateCtrl.html', //TODO : replace with the good template
controller: 'CandidateCtrl'
}).
when('/person/:uuid/confirm', {
templateUrl: 'partials/ConfirmCtrl.html', //TODO : replace with the good template
controller: 'ConfirmCtrl'
}).
when('/person/add', {
templateUrl: 'partials/AddCtrl.html', //TODO : replace with the good template
controller: 'AddCtrl'
}).
otherwise({
redirectTo: 'Something' //TODO : replace with the good url
});
}]);
I was serving the views by via my web-mvc. I've since changed it to serve a layout and have the partial pages be kept in the resource folder.
I have multiple routes that invoke the same Controller and I would like to pass different variables to it.
// Example
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleB'
});
I know that I could use the "resolve" object:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
resolve: {test: function() { return true; }}
});
To pass a value as a dependency:
app.controller('MyController', ['$scope', 'test', function ($scope, test) {
console.log(test); // true
}
My problem with that approach is that my app crashes if the resolve object is missing on other routes and I would like to pass optional params.
Is there any way to pass specific params to the Controller (from the route provider)?
Thank you
Routing:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleB'
});
Access: inject $route in your controller then use this
app.controller('MyController', ['$scope', '$route', function ($scope, $route) {
var paramValue = $route.current.$$route.paramExample;
console.log(paramValue);
}
You can use resolve and $route.currrent.params.test to pass the parameter like this:
$routeProvider
.when('/a', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = true; }
}
})
.when('/b', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = false; }
}
})
Then in your controller you can access it from the $routeParams:
app.controller('MainCtrl', function($scope, $routeParams) {
$scope.test = $routeParams.test;
})
http://plnkr.co/edit/ct1ZUI9DNqSZ7S9OZJdO?p=preview
The most natural way to do this is doing what you would normally do when you want to load a page with parameters: use query parameters: http://yoururl.com?param1=value¶m2=value
ngRoute comes with the service $routeParams which you can inject in your controller. Now you can simply retrieve the values like this $routeParams.param1.
Another way to do this is to retrieve the path with $location.path and set the variable there.
using $routeParams
in Main js file
routeApp.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: '../sites/./home.html',
controller: 'StudentController'
})
.when('/viewStudents/:param1/:param2', {
templateUrl: '../sites/./viewStudents.html',
controller: 'StudentController'
})
.otherwise({
redirectTo: '/'
});
});
routeApp.controller('StudentController',['$filter','$routeParams', '$location',function($filter,$routeParams,$location){
var StudentCtrl = this;
StudentCtrl.param1 = $routeParams.param1;
StudentCtrl.param2 = $routeParams.param2;
}]);
calling from Home.html
<div class="container">
<h2> Welcome </h2>
Students
</div>
I have an rest api, in which the api is sending instruction to redirect (301 is being sent).
And I have my angular js code like this:
var request = $http.post(LOGIN_URL,{username:'tes',password:'test'})
request.success(function(html)
{
if(html.failure) {
console.log("failure")
$scope.errorMessage = html.failure.message
}
else {
console.log("Success here....")
$location.path("route")
}
})
I can see in the browser log that it is coming in the else part ( Success here..... is being printed). But the url is not changed. $location.path doesnt do anything; I have also tried $location.url which also results the same thing.
And also I'm injecting the $location to my controller.
Where I'm making mistake?
Thanks in advance.
Try something like this
$location.path("/myroute")
You have to have a ng-view on the page as well.
Also make sure you have a corresponding view with that name
and when you're registering your controller you have the '$location' var being injected in the declaration of your controller like this example:
controllers.controller('MyCtrl', ['$scope', '$route', '$location', 'MYService',
function($scope, $route, $location, MyService) {
// ... controller code
}])
also you might want to debug your route changing to see what is happening with a location change listener, like in this example:
return app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'MyCtrl'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
when('/error/:errorId', {
templateUrl: 'partials/error.html',
controller: 'ErrorCtrl'
}).
otherwise({
redirectTo: '/home'
});
}]).run(function($rootScope, $injector, $location) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
console.log('current=' + current.toString());
console.log('next=' + next.toString());
});
});
});
is it possible to load url from controllers in routeProvider?
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/LALA', {
controller: 'LalaController',
templateUrl: '/mlala.html'
})
.when('/HOHO', {
controller: 'HohoController',
templateUrl: '/hoho.html'
})
.otherwise({redirectTo: '/'});
and I would like something like this:
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/MO', {
controller: 'MOController',
templateUrl: $scope.url
})
.when('/MOCache', {
controller: 'MOCacheController',
templateUrl: $scope.url
})
.otherwise({redirectTo: '/'});
Route URLs would be defined in Controllers.
Well, no.
But you can use named groups, assign a function to templateUrl and get the route parameters passed in:
.when('/MO/:page', { // <-- ':page' is a named group in the pattern
controller: 'MOController',
templateUrl: function (params) {
// use the route parameters to return a custom route
return 'views/partials/mo/' + params.page + '.html';
}
})
Than you can just inject whatever custom parameter you like in your views, e.g.:
<!-- 'paws' and 'whiskers' will be passed to the route params -->
paws page!
whiskers page!
Look, mommy, no controllers!
Reference
$routeProvider on the AngularJS docs.