Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Pre-served $params variables for a controller defined inside of a route

Tags:

angularjs

Is it possible to pass your own variables in a defined route in AngularJS?

The reason why I'm doing this is because I have to data representations of the same page (one is a filtered view in terms of the JSON data) and all I need to do is give a boolean flag to the $params array to let the controller function know that this page is either filtered or non-filtered.

Something like this:

var Ctrl = function($scope, $params) {
  if($params.filtered) {
    //make sure that the ID is there and use a different URL for the JSON data
  }
  else {
    //use the URL for JSON data that fetches all the data
  }
};

Ctrl.$inject = ['$scope', '$routeParams'];

angular.modlule('App', []).config(['$routeProvider', function($routes) {

  $routes.when('/full/page',{
    templateURL : 'page.html',
    controller : Ctrl
  });

  $routes.when('/full/page/with/:id',{
    templateURL : 'page.html',
    controller : Ctrl,
    params : {
      filtered : true
    }
  });

}]);
like image 268
matsko Avatar asked Aug 21 '12 17:08

matsko


1 Answers

According to $routeProvider documentation, the route parameter of $routeProvider.when() has property resolve:

An optional map of dependencies which should be injected into the controller.

Something like this should work:

function Ctrl($scope, isFiltered) {
  if(isFiltered) {
    //make sure that the ID is there and use a different URL for the JSON data
  }
  else {
    //use the URL for JSON data that fetches all the data
  }
}
Ctrl.$inject = ['$scope', 'isFiltered'];

angular.modlule('App', []).config(['$routeProvider', function($routeProvider) {

  $routeProvider.when('/full/page',{
    templateURL: 'page.html',
    controller: Ctrl
  });

  $routeProvider.when('/full/page/with/:id',{
    templateURL: 'page.html',
    controller: Ctrl,
    resolve: {
      isFiltered: function() { return true; }
    }
  });

}]);
like image 190
Marcello Nuccio Avatar answered Oct 19 '22 22:10

Marcello Nuccio