Pass parameters to controller in defined route? - angularjs

Say I have an app defined as such:
angular.module('myApp', ['myControllers'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'myTemplate.html',
controller: 'MyController'
//???
})]);
How can I say, set $scope.myVariable via this route definition? I want to use this for breadcrumbs.

I think a better way to do what you are doing is to use route parameters. See
https://docs.angularjs.org/api/ngRoute/service/$routeParams
You can make your route something like
/Chapter/:chapterId
and in your controller, inject $routeParams and access the value like so:
$routeParams.chapterId

Turns out you can use the resolve property in the .when method like so:
.when('/', {
templateUrl: 'myTemplate.html',
controller: 'MyController',
resolve: {
test: function() {return "test";}
}
});
Then in my controller I don't access it via the $scope but I inject it like so:
.controller('MyController', ['$scope', 'test', function($scope, test) {
//test contains "test"
}]);

Related

how to implement Rooting angularJS with customize url

I want to have on the URL of my application like this:
http://localhost:9000/#/?id=XYZ
I don't found how to configure this on angularjs app module
My implementation is like that:
angular.module('APP', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider.when("/?id="+":id", {
templateUrl: "views/sign/sign.html",
controller: "SignCtrl"
});
// $locationProvider.html5Mode(true);
});
but It doesn't work.
You do not have to specify
it will be like
angular.module('APP', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider.when("/", {
templateUrl: "views/sign/sign.html",
controller: "SignCtrl"
});
// $locationProvider.html5Mode(true);
});
and in your SingCtrl.
when you write $routeParam than you will have objects of params which are passed as a query parameter.
so you will get $routePara.id if you pass like ?id=anything
Do not have to worry if you want to catch the query param like ?id=abs&name=test
You can add a "url" attribute to your $routeProvider object.
Something like:
$routeProvider.when("/?id="+":id", {
templateUrl: "views/sign/sign.html",
url: 'the Url you want to use',
controller: "SignCtrl"
});
PS.: I suggest you to use ui-router instead of ngRoute. Check it out later.

how to inject $attrs into a controller through $routeProvider

I have a mini app with a controller that looks like that:
app.controller("MyController", [ '$scope', '$attrs', 'ServiceA', 'ServiceB', function($scope, $attrs, svc1, svc2) {
...
}])
When I tried to add angular-routing to my app, I added the following route.js file:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/main.html',
controller: 'MyController',
controllerAs: 'appCtrl',
resolve: {
attrs: $attrs
}
})
}
]);
It seems that I can't inject $attrs like before. I've tried playing with resolve inside when() but it didn't seem to help.
I must say it looks a bit weird to inject $attrs into the controller anyway, and since that's my first app I think I'm doing something wrong here.. I need $attrs to read a data attribute from the div and initialize some array according to it. Any ideas to how I should do it or why I couldn't do it with my approach? (which worked without the routes)
Thanks!

$routeParams not defined. I am not sure what I changed to make it not work suddenly

I am not sure what is going on here.
angular.module('myApp', [
'ngRoute',
'myApp.controllers',
'myApp.filters',
'myApp.services',
'myApp.directives'
]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: '/partials/homepage',
controller: 'MyCtrl1'
}).
when('/about/:id', {
templateUrl: '/partials/'+$routeParams.id,
controller: 'MyCtrl1'
}).
when('/funnel', {
templateUrl: '/partials/funnel',
controller: 'MyCtrl2'
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
No matter if I browse to / or /about/:id I get $routeParams is undefined.
You need to inject $routeParams service to use it. However in your case looks like you want to dynamically determine the template based on the routeparam. You cannot directly do it in the config phase of the app, which runs only once as a part of app initialization stage (and also you can inject $routeParams in the config phase of the app since there is no such provider). You you may want to look for a way to retrieve dynamic template and in order to support this angular provides this facility to use function as templateUrl to be able to dynamically determine the template url based on any routeparameters (which will be argument in the function).
You can do it this way:-
when('/about/:id', {
templateUrl: function(routeParam){ //register it as function
return '/partials/' + routeParam.id; //Get the id from the argument
},
controller: 'MyCtrl1'
}).
Right from documentation.
templateUrl – {string=|function()=} – path or function that returns a path to an html template that should be used by ngView.
If templateUrl is a function, it will be called with the following parameters:
{Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
It's because of this line:
templateUrl: '/partials/'+$routeParams.id,
You're using $routeParams without every declaring or injecting it. If you add it to the params your function accepts, your page should stop throwing that error:
config(function ($routeProvider, $routeParams, $locationProvider) {
// ...
}

Dynamic routeProvider parameters for angular router

I am trying to take advantage of the back button's history, and so I am using the traditional $routeProvider and a url of
.../arg1/something/arg2/something,else/arg3/another/arg4/yet,another/arg5/final
However, if one argument is missing, the following route provider will fail to pass the remaining arguments to the $routeParams:
angular.module('myApp', [ … ])
.config(function ($routeProvider) {
$routeProvider
.when('/arg1/:args1/arg2/:args2/arg3/:args3/arg4/:args4/arg5/:args5', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.otherwise({
redirectTo: '/'
});
});
How do I configure the $routeProvider to pass the arguments that are present, (in any order if possible, if not at least in the order that but account for absence of an argument), to the controller without having to declare all 720 (6!) different scenarios of different arguments in different order or not at all?
I then plan to use these values to populate the filters in the controller via the following:
function filterRouteParams (rp){
if(rp.args1){
$scope.args1 = rp.args1;
}
if(rp.args2){
$scope.args2 = rp.args2.split(',');
}
if(rp.args3){
$scope.args3 = rp.args3.split(',');
}
…
}
I am a little familiar with using the ? query on the URL, but to my knowledge, I don't know how to bind that to the history when I want to update it and also allow for using the back button and maintain the query, but am open to being schooled!
Do I not understand ur question, or it just got complicated?
You just SIMPLY use query string for this purpose.
It works perfectly fine with back and forward buttons, history push/state.
angular.module('myApp', ['ngRoute'])
.controller('MainController', function($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
})
.controller('FilterController', function($scope, $routeParams) {
})
.config(function($routeProvider) {
$routeProvider
.when('/filter', {
template: 'inside filter',
controller: 'FilterController'
})
.otherwise({
redirectTo: '/filter'
});
});
This is the running example of the above code, http://run.plnkr.co/plunks/OS38E38J11FeDS1hyHde/#/filter?c=3&d=4
and Here is the plnkr.
I think the best way of handling this is through query string parameters, so your route is defined like this:
.when('/filter', {
controller: 'MainController'
})
And you just use a URL like /filter?foo=44&bar=123&baz=true, or in code:
$location.path('/filter').search('foo', $scope.fooValue).search('bar', $scope.barValue);
Parameters are optional and be specified in any order as ngRoute does not do any validation of param names or values.
To access the values in your controller:
.controller('MainController', function($scope, $routeParams) {
if ($routeParams.foo) {
// do argument processing
}
})
docs for $routeParams: https://docs.angularjs.org/api/ngRoute/service/$routeParams
I'm not sure to really understand, but could you use '?' inside your routes ? for example
$routeProvider
.when('/arg1/:args1?/arg2/:args2?/arg3/:args3?/arg4/:args4?/arg5/:args5?', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.otherwise({
redirectTo: '/'
});
Any of the following URL would be valid
/arg1/arg2/arg3/arg4/arg5
/arg1/value1/arg2/arg3/arg4/arg5/value5
....
/arg1/value1/arg2/value2/arg3/value3/arg4/value4/arg5/value5
Is that what you were looking for?
Unfortunately I couldn't find a way to remove an argument like this
/arg1/arg2/arg4/value4/arg5/value5

Custom state-enter and state-exit code with routing

I have a fairly simple Angular project which routes to a couple different URLs in the JavaScript:
function RootController($scope) {};
function PageOneController($scope) {};
angular.module('mymodule', []).config(
['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: "templates/root.html",
controller: RootController
}).when('/page1/', {
templateUrl: "templates/page1.html",
controller: PageOneController
}).otherwise({redirectTo: '/'});
}]
);
Everything works great so far, but I do need a way to have some JavaScript function run on when these routes are entered and exited. ie:
$routeProvider.when('/', {
templateUrl: "templates/root.html",
controller: RootController,
onenter: function() { console.log("Enter!"); },
onexit: function() { console.log("Exit!"); }
});
Is there a way to do this in Angular? On enter of a state/route, I need to bind event listeners, and on exit I need to destroy them and tear down.
$route service has two events $routeChangeStart and $routeChangeSuccess, these can be of some help for you.
You can use $routeChangeStart before exiting and $routeChangeSuccess on entering.
You can do $scope.$on on any controller to watch for these events.

Resources