AngularJS: Parameterize controller via route

Issue

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) { .. }]);

Solution

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);
});

Answered By – rayners

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.