我需要加载网络服务。我喜欢显示、排序和过滤表格的 Angular 方式,而且我构建的效果非常好。现在我正在尝试扩展此功能:根据所选的链接,我想以相同的方式显示不同的数据,但来自相同的网络服务。我试图不重复代码,所以我试图重用 Controller ,但现在我很困惑。这意味着我想要
- 显示不同的部分/模板网址。
- 加载不同的网址参数。
- 返回 JSON 后映射一些内容。
解决我迄今为止认为的更多配置更改的最佳方法是什么?我首先路由到一个变量 ( when('/change-requests/:businessUnit'
),然后使用它来加载不同的值。但是,我该如何更改模板网址呢?另一方面,如果我只是添加一个路由并加载不同的 URL 模板(重用 Controller ),如何在 ajax 调用中加载不同的 url?我对 Angular 不太熟悉,所以也许我找错了对象......
这是我原始代码的相关部分。还有更多的事情,但这些都不需要改变。我已经添加了一些内联注释,您可以在其中找到我想要更改的位,具体取决于所选的链接。
HTML:
<div ng-view></div>
路由器:
$routeProvider.when('/change-requests/business-solutions', {
//this template will be different
templateUrl: 'js/modules/changeRequests/partials/business-solutions.html',
controller: ChangeRequestCtrl
})
(部分) Controller :
function ChangeRequestCtrl($scope, $location) {
$scope.loaded = false;
$.ajax({
//this url will be different
url: url,
success: function(json) {
$scope.$apply(function() {
$scope.changes = json.map(function(row) {
//this array map will be different
return row;
});
$scope.loaded = true;
});
},
error: function() {
$scope.error = true;
}
});
}
如果我没有理解清楚,我会尽力澄清。
最佳答案
如果您想使用重用 Controller 名称,那么您应该将解析属性与路由一起使用,并在 Controller 中使用该解析属性
$routeProvider.when('/change-requests/business-solutions', {
//this template will be different
templateUrl: 'js/modules/changeRequests/partials/business-solutions.html',
controller: ChangeRequestCtrl, resolve: {
resolvedprop: ['$route', '$q', function ($route, $q) {
var apiObject = {url: 'abc.com' };
return apiObject
}],
}
})
function ChangeRequestCtrl($scope, $location,resolvedprop) {
url = resolvedprop.url ;
}
关于javascript - 如何根据路线重用具有不同变量的AngularJS Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17716871/