Reputation: 2298
I use the same controller for multiple views. I want to parameterize the controller differently depending on the route taken.
The views display basically the same angular ui grid, hence the same controller. However, in one view I want to pre-filter the grid for specific data, whereas in the other I don't.
How can I do that?
app.config(function ($routeProvider) {
$routeProvider
.when('/foo',
{
controller: 'Ctrl',
templateUrl: '/foo.html',
})
.when('/bar',
{
controller: 'Ctrl',
templateUrl: '/bar.html',
});
});
app.controller('Ctrl', ['$scope' function ($scope) { .. }]);
Upvotes: 1
Views: 54
Reputation: 939
Think of it that way.
Both routes are the same except one has a filter and one doesn't. so in reality it's the same route with additional parameter filter='some'
right so your configuration might be something like this:
app.config(function ($routeProvider) {
$routeProvider
.when('/foo/:filter?',
{
controller: 'Ctrl',
templateUrl: '/foo.html',
})
});
and in your controller you'll have $routeParams.filter
question mark would be an optional parameter. Then in the Ctrl
you would just look for filter parameter and use filter to render appropriately.
Btw your view can stay the same just filter your grid anyways. if filter param doesn't exist it will just return same data (unfiltered)
Hope that helps.
Upvotes: 2
Reputation: 539
At the basic level, you could inspect the current route to see what template was being used and branch off that.
app.controller('Ctrl', function($route) {
if ($route.current.templateUrl === '/foo.html') {
doFoo();
} else {
doBar();
}
});
That would only work if you are using different templates for each route. If you wanted to re-use the same template, the resolve
property of the route is very useful.
app.config(function($routeProvider) {
$routeProvider.when('/foo', {
controller: 'Ctrl',
templateUrl: '/foo.html'
resolve: {
whichRoute: function() { return 'foo'; }
}
});
});
app.controller('Ctrl', function(whichRoute) {
if (whichRoute === 'foo') {
doFoo();
} else {
doBar();
}
});
And even better than that, the resolve
properties can accept functions that return values or promises, so you could do the pre-filtering of the data in there.
app.config(function($routeProvider) {
$routeProvide.when('/foo', {
controller: 'Ctrl',
templateUrl: '/foo.html',
resolve: {
dataToDisplay: function(YourDataService) {
return YourDataService.getSomeData();
}
}
});
});
app.controller('Ctrl', function(dataToDisplay) {
doTheThing(dataToDisplay);
});
Upvotes: 1