AngularJS为路由内定义的控制器预先提供$ params变量

mat*_*sko 8 angularjs

是否可以在AngularJS中的已定义路径中传递您自己的变量?

我这样做的原因是因为我必须对同一页面的数据表示(一个是根据JSON数据的过滤视图),我需要做的就是给$ params数组一个布尔标志让let控制器功能知道此页面已过滤或未过滤.

像这样的东西:

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

}]);
Run Code Online (Sandbox Code Playgroud)

Mar*_*cio 21

根据$routeProvider文档,route参数$routeProvider.when()有属性resolve:

应该注入控制器的可选依赖关系映射.

这样的事情应该有效:

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

}]);
Run Code Online (Sandbox Code Playgroud)