Angular ui-router 允许我解决可以在我的 Controller 中使用的不同注入(inject)。
我创建了一个简单的通用 ListController,并在 ui-router 中注入(inject)了一个对象,该对象包含特定于该特定 View 的 CRUD 函数以及模板。
因此,例如,假设我有 2 个具有相同“crud”语法的服务:
addPerson(person, callback){}
deletePerson(person, callback){}
editPerson(person, callback){}
....
addCar(car, callback){}
deleteCar(car, callback){}
editCar(car, callback){}
....
我创建了一个映射对象来将这些服务的 CRUD 函数映射到我的通用 Controller 中,该 Controller 是通过 ui.router 注入(inject)的。
通用 Controller :
controller('ListCtrl', ['$scope', 'itemList', 'functions', function ($scope, itemList, functions) {
$scope.itemList = itemList;
$scope.addItem = function(){
functions.add($scope.item, callback);
}
.....
}
路由器:
.state('app.people', {
url: '/people',
templateUrl: 'views/people.html',
resolve: {
functions: ['People', function(People){
return {
add: People.createPerson,
update: People.updatePerson,
delete: People.deletePerson,
getItemList: People.getPeopleList
}
}],
itemList: ['$q', 'People', function($q, People){
var deferred = $q.defer();
People.getPeopleList(function(resp, status){
deferred.resolve(resp);
});
return deferred.promise;
}],
},
controller: 'GenericController'
})
因此,您也可以将它与汽车一起使用,只需在其状态定义中注入(inject)不同的函数映射即可。
奇迹般有效。
但现在我希望能够在 div 中使用我的 Controller ,而不仅仅是在全 View 中。现在问题来了:
如果我使用 ng-controller 指令,注入(inject)器将不知道提供什么作为 'itemList' 或 'functions'(这是映射对象),但如果我通过 $controller 对象实例化它,那么它不会没有自己的范围,我得到一个
Unknown provider: $scopeProvider <- $scope
因为它将无法创建自己的子范围..
我想我可以通过 $rootScope.$new() 或类似的东西创建一个新范围,但感觉太像黑客了,而且由于我是 Angular 新手,我认为这对于类似的东西来说可能是一个不好的方法这..
有小费吗?
最佳答案
为了将来引用,我最终编写了一个由通用 Controller 和微型专用 Controller 组成的系统that extend them .
对于上面的示例,通用 Controller 是“PeopleController”和“CarController”的子类。在 Controller 代码的开头,它们中的每一个都将执行以下操作:
controller('PeopleController', ['$scope', 'peopleService', function ($scope, peopleService) {
angular.extend(this, $controller('listController', {$scope: $scope, functions:{
add: peopleService.addPerson,
remove: peopleService.removePerson,
[...]
}}));
$scope.people = $scope.itemList;
}
所以现在我可以自己实例化 Controller ,甚至在 ng-controller 指令中,他们将为所有 CRUD 方法使用通用 Controller 。
关于angularjs - 创建一个通用的 angularjs listController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27061890/