AngularJS: 通过路由参数化控制器

AngularJS: Parameterize controller via route

我对多个视图使用同一个控制器。我想根据所走的路线对控制器进行不同的参数化。

视图显示基本相同的 angular ui 网格,因此控制器相同。但是,在一个视图中我想为特定数据预过滤网格,而在另一个视图中我不想。

我该怎么做?

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

在基本级别,您可以检查 current route 以查看正在使用的模板并将其分支。

app.controller('Ctrl', function($route) {
  if ($route.current.templateUrl === '/foo.html') {
    doFoo();
  } else {
    doBar();
  }
});

这只有在您为每条路线使用不同的模板时才有效。如果您想重复使用相同的模板,resolve property of the route 非常有用。

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

甚至比这更好的是,resolve 属性可以接受 return 值 承诺的函数,因此您可以进行预过滤那里的数据。

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

这样想。 除了一条有过滤器而一条没有过滤器之外,这两条路线是相同的。所以实际上它是带有附加参数 filter='some' 的相同路由,因此您的配置可能是这样的:

app.config(function ($routeProvider) {
$routeProvider
    .when('/foo/:filter?',
        {
            controller: 'Ctrl',
            templateUrl: '/foo.html',
        })
});

并且在您的控制器中您将有 $routeParams.filter 问号将是一个可选参数。然后在 Ctrl 中,您只需查找 filter 参数并使用 filter 进行适当渲染。 顺便说一句,您的视图可以保持不变,只需过滤您的网格即可。如果过滤器参数不存在,它将只是 return 相同的数据(未过滤)

希望对您有所帮助。