对于多个视图Angularjs控制器 [英] Angularjs controller for multiple views
问题描述
如果我需要重复使用以下控制器(放置在App.js),我需要删除该视图特定columnDefs并分别把它们(视图,HTML文件)。
在这里,我有UI电网的 gridOptions
在控制器中设置。即使我管理的地方,在UI(script标签), uiGridConstants 是不是在视图中可用。那么,如何去了解这个,所以我可能会重用多个视图文件。
我拉我的头发很长一段时间了,而且我对角度的新手,所以请大家帮忙。
(函数(){
gridFactory =功能($ HTTP){
返回{
callWebApi:功能(){
返回$ HTTP({
方法:GET,
网址:'/ API / PatientCategoryApi / PatCat',
params:一个this.callParams.paginationOptions,
标题:{内容类型:应用/ JSON的'}
})
},
callParams:{}
}
};
patientCategoryController =功能($范围,$ ATTRS,uiGridConstants,gridFactory){ $ scope.gridOptions = { paginationPageSizes:[5,10,20,25,50],
paginationPageSize:10,
useExternalPagination:真实,
useExternalSorting:真实,
enableSorting:真实,
的rowHeight:30,
columnDefs:
{场:'ID',sortDirectionCycle:[uiGridConstants.ASC,uiGridConstants.DESC]},
{场:'code'},
{场:名称},
{场:描述},
{场:'ModifiedTime',cellFilter:日期:DD-MMM-YY H:MM:SS A},
{场:'历史',enableSorting:假}
]
onRegisterApi:功能(gridApi){
$ scope.gridApi = gridApi;
}
}; 变种callData = {}; 变种paginationOptions = {};
paginationOptions.Page = 1;
paginationOptions.Take = 10;
paginationOptions.SortOrder ='升序';
paginationOptions.PropName ='ID';
callData.paginationOptions = paginationOptions;
gridFactory.callParams = callData;
VAR承诺= gridFactory.callWebApi();
promise.then(
功能successCallback(响应){
$ scope.gridOptions.totalItems = response.data.TotalCount;
$ scope.gridOptions.data = response.data.Collection;
$ scope.gridHeight = gridFactory.getGridHeight($ scope.gridOptions);
},功能errorCallback(响应){
警报('一些问题,同时读取数据!');
});
}
。patientCategoryController $注射='$范围,$ ATTRS','uiGridConstants','gridFactory'];
。gridFactory $注射='$ HTTP'];
angular.module('abvhHisApp',['ui.grid','ui.grid.autoResize','ui.grid.pagination','ui.grid.resizeColumns']);
angular.module('abvhHisApp')控制器('patientCategoryController',patientCategoryController)。
angular.module('abvhHisApp')工厂('gridFactory',gridFactory)。
}());
我有完全相同带有多个网格视图同样的问题,想写DRY code。
我的解决方案是创建一个基类为网格控制器和继承它的不同的看法。
基类(为电网提供无限滚动):
块引用>
\r\r\r\r函数InfiniteGrid(){\r
VAR VM =这一点;\r
\r
vm.firstPage = vm.lastPage = 1;\r
vm.keepPages = 3;\r
vm.pageSize = 100;\r
vm.totalCount = 0;\r
\r
vm.init();\r
\r
vm.data = vm.loadData();\r
\r
vm.uiGridOptions = {\r
enableSorting:真\r
,columnDefs:vm.columnDefs\r
数据:'vm.data\r
,infiniteScrollRowsFromEnd:1\r
,infiniteScrollUp:真\r
,infiniteScrollDown:真\r
,onRegisterApi:功能(gridApi){\r
gridApi.infiniteScroll.on.needLoadMoreData(VM $范围,vm.getDataDown);\r
gridApi.infiniteScroll.on.needLoadMoreDataTop(VM $范围,vm.getDataUp);\r
vm.gridApi = gridApi;\r
}\r
};\r
\r
虚拟机。$范围。$腕表('vm.filterText',函数(搜索){\r
vm.firstPage = vm.lastPage = 1;\r
vm.data = vm.loadData(1,搜索);\r
});\r
\r
}\r
\r
InfiniteGrid.prototype = {\r
loadData:功能(页面,搜索){\r
VAR VM =这一点;\r
返回vm.Entity.query({页:页面,限制:vm.pageSize,搜索:搜索},功能(数据头){\r
vm.totalCount = data.total_count = 1 *标题(X-名单计);\r
虚拟机。$超时(函数(){\r
vm.gridApi.infiniteScroll.dataLoaded(vm.firstPage大于1,vm.lastPage&所述; Math.floor(vm.totalCount / vm.pageSize)+1);\r
});\r
});\r
},\r
getDataDown:功能(){\r
VAR gridApi =这一点,\r
VM = gridApi.grid.appScope.vm;\r
vm.loadData(vm.lastPage + 1)。$ promise.then(功能(newData){\r
vm.lastPage ++;\r
gridApi.infiniteScroll.saveScrollPercentage();\r
vm.data = vm.data.concat(newData);\r
gridApi.infiniteScroll.dataLoaded(vm.firstPage大于1,vm.lastPage&所述; Math.floor(newData.total_count / vm.pageSize)+1)\r
。然后(vm.checkDataLength.bind(VM,'达'));\r
});\r
},\r
\r
getDataUp:功能(){\r
VAR gridApi =这一点,\r
VM = gridApi.grid.appScope.vm;\r
vm.loadData(vm.firstPage - 1)$ promise.then(功能(newData){\r
vm.totalCount = newData.total_count;\r
vm.firstPage--;\r
gridApi.infiniteScroll.saveScrollPercentage();\r
vm.data = newData.concat(vm.data);\r
gridApi.infiniteScroll.dataLoaded(vm.firstPage大于1,vm.lastPage&所述; Math.floor(newData.total_count / vm.pageSize)+1)\r
。然后(vm.checkDataLength.bind(VM,'下'));\r
});\r
},\r
\r
checkDataLength:功能(方向){\r
VAR VM =这一点;\r
如果(vm.lastPage - vm.firstPage> vm.keepPages){\r
如果(方向==='了'){\r
vm.data = vm.data.slice(vm.pageSize);\r
vm.firstPage ++;\r
虚拟机。$超时(函数(){\r
vm.gridApi.infiniteScroll.dataRemovedTop(vm.firstPage大于1,vm.lastPage&所述; Math.floor(vm.totalCount / vm.pageSize)+1);\r
});\r
}其他{\r
vm.data = vm.data.slice(0,vm.pageSize * vm.keepPages);\r
vm.lastPage--;\r
虚拟机。$超时(函数(){\r
vm.gridApi.infiniteScroll.dataRemovedBottom(vm.firstPage大于1,vm.lastPage&所述; Math.floor(vm.totalCount / vm.pageSize)+1);\r
});\r
}\r
}\r
},\r
\r
deleteRow:功能(ROWID){\r
VAR VM =这一点,\r
。行= $ VM滤波器('过滤器')(vm.data,{_id:ROWID})[0]\r
rowIdx = vm.data.indexOf(行);\r
\r
vm.Entity.delete({ID:ROWID})$ promise.then(函数(){\r
vm.data.splice(rowIdx,1);\r
vm.toastr.success(记录删除成功!,成功,{extendedTimeOut:1500,超时:1500});\r
},功能(数据,状态){\r
如果(状态!== 401){\r
vm.toastr.error(data.data.message);\r
}\r
});\r
}\r
};\r
\r
返回InfiniteGrid;\r
});\r
继承控制器code
块引用>
\r\r\r\rangular.module('对myApp')\r
.controller('SomeGridCtrl',['$范围,$超时','$资源','toastr','$过滤器,$ routeParams',SomeGridCtrl]);\r
\r
功能SomeGridCtrl($范围,$超时,$资源,toastr,$过滤器,$ routeParams)\r
{\r
VAR VM =这一点;\r
$ scope.vm = VM;\r
。VM $范围= $范围;\r
vm.toastr = toastr;\r
。VM $过滤器= $滤波器;\r
。VM $超时= $超时;\r
。VM $资源= $资源;\r
VM $ routeParams = $ routeParams。\r
\r
//调用父类的构造\r
infiniteGrid.call(VM);\r
}\r
\r
//继承原型\r
SomeGridCtrl.prototype =的Object.create(infiniteGrid.prototype);\r
\r
SomeGridCtrl.prototype.init =功能(){\r
VAR VM =这一点;\r
\r
vm.Entity = $ VM资源('/ API /项目/:身份证')。\r
vm.columnDefs = [\r
{\r
显示名:标题\r
,场:标题\r
//,过滤器:文本,\r
,cellTemplate:'< DIV CLASS =UI并网细胞内容><一个NG-HREF =#/卡/ {{row.entity._id}}NG绑定=COL_FIELD&GT ;< / A>< / DIV>'\r
},{\r
显示名:URL\r
,场:URL\r
,过滤器:文本\r
,cellTemplate:'< DIV CLASS =UI并网细胞内容><一个NG-HREF =#/卡/ {{row.entity._id}}NG绑定=COL_FIELD&GT ;< / A>< / DIV>'\r
},{\r
显示名:合作伙伴\r
,场:partner.fullName\r
//,过滤器:文本\r
},{\r
现场:REVIEW_COUNT\r
,显示名:评论\r
,宽度:80\r
,cellTemplate:'< DIV CLASS =UI并网细胞内容><一个NG-HREF =#/卡/ {{row.entity._id}} /评论NG绑定=COL_FIELD >< / A>< / DIV>'\r
},{\r
显示名:创建于\r
,场:创造\r
,cellFilter:amCalendar\r
,过滤器:假的\r
},{\r
显示名:删除\r
,场:虚拟\r
//,宽度:80\r
,cellTemplate:'< DIV CLASS =UI并网细胞内容><一个NG点击=grid.appScope.vm.deleteRow(row.entity._id)确认=你确定吗? 类=BTN BTN-XS BTN-危险>删除< / A>< / DIV>'\r
}\r
];\r
};\r
If I need to reuse the following controller(placed in App.js), I need to remove the view specific columnDefs and place them separately(View, html file).
Here I have ui-grid's
gridOptions
set in the controller itself. Even if I manage to place that in UI(script tag), uiGridConstants is not available in the view. So how do I go about with this so I may reuse the file for multiple views. I am pulling my hair for quite some time now, and am a newbie on angular, so please help.(function () { gridFactory = function ($http) { return { callWebApi: function () { return $http({ method: 'GET', url: '/api/PatientCategoryApi/PatCat', params: this.callParams.paginationOptions, headers: { 'Content-Type': 'application/Json' } }) }, callParams: {} } }; patientCategoryController = function ($scope, $attrs, uiGridConstants, gridFactory) { $scope.gridOptions = { paginationPageSizes: [5, 10, 20, 25, 50], paginationPageSize: 10, useExternalPagination: true, useExternalSorting: true, enableSorting: true, rowHeight: 30, columnDefs: [ { field: 'Id', sortDirectionCycle:[uiGridConstants.ASC, uiGridConstants.DESC] }, { field: 'Code' }, { field: 'Name' }, { field: 'Description' }, { field: 'ModifiedTime', cellFilter: 'date:"dd-MMM-yy h:mm:ss a"' }, { field: 'History', enableSorting: false } ], onRegisterApi: function (gridApi) { $scope.gridApi = gridApi; } }; var callData = {}; var paginationOptions = {}; paginationOptions.Page = 1; paginationOptions.Take = 10; paginationOptions.SortOrder = 'Asc'; paginationOptions.PropName = 'Id'; callData.paginationOptions = paginationOptions; gridFactory.callParams = callData; var promise = gridFactory.callWebApi(); promise.then( function successCallback(response) { $scope.gridOptions.totalItems = response.data.TotalCount; $scope.gridOptions.data = response.data.Collection; $scope.gridHeight = gridFactory.getGridHeight($scope.gridOptions); }, function errorCallback(response) { alert('Some problem while fetching data!!'); }); } patientCategoryController.$inject = ['$scope', '$attrs', 'uiGridConstants', 'gridFactory']; gridFactory.$inject = ['$http']; angular.module('abvhHisApp', ['ui.grid', 'ui.grid.autoResize', 'ui.grid.pagination', 'ui.grid.resizeColumns']); angular.module('abvhHisApp').controller('patientCategoryController', patientCategoryController); angular.module('abvhHisApp').factory('gridFactory', gridFactory); }());
解决方案I had exactly the same problem having a number of grid views and wanted to write DRY code. My solution was to create a base class for the grid controllers and inherit it for different views.
Base class (providing infinite scrolling for the grid):
function InfiniteGrid() { var vm = this; vm.firstPage = vm.lastPage = 1; vm.keepPages = 3; vm.pageSize = 100; vm.totalCount = 0; vm.init(); vm.data = vm.loadData(); vm.uiGridOptions = { enableSorting: true ,columnDefs: vm.columnDefs ,data: 'vm.data' ,infiniteScrollRowsFromEnd: 1 ,infiniteScrollUp: true ,infiniteScrollDown: true ,onRegisterApi: function(gridApi){ gridApi.infiniteScroll.on.needLoadMoreData(vm.$scope, vm.getDataDown); gridApi.infiniteScroll.on.needLoadMoreDataTop(vm.$scope, vm.getDataUp); vm.gridApi = gridApi; } }; vm.$scope.$watch('vm.filterText', function(search){ vm.firstPage = vm.lastPage = 1; vm.data = vm.loadData(1, search); }); } InfiniteGrid.prototype = { loadData : function (page, search) { var vm = this; return vm.Entity.query({page: page, limit: vm.pageSize, search: search}, function (data, headers) { vm.totalCount = data.total_count = 1 * headers('X-List-Total'); vm.$timeout(function () { vm.gridApi.infiniteScroll.dataLoaded(vm.firstPage > 1, vm.lastPage < Math.floor(vm.totalCount / vm.pageSize) + 1); }); }); }, getDataDown : function () { var gridApi = this, vm = gridApi.grid.appScope.vm; vm.loadData(vm.lastPage + 1).$promise.then(function (newData) { vm.lastPage++; gridApi.infiniteScroll.saveScrollPercentage(); vm.data = vm.data.concat(newData); gridApi.infiniteScroll.dataLoaded(vm.firstPage > 1, vm.lastPage < Math.floor(newData.total_count / vm.pageSize) + 1) .then(vm.checkDataLength.bind(vm, 'up')); }); }, getDataUp : function () { var gridApi = this, vm = gridApi.grid.appScope.vm; vm.loadData(vm.firstPage - 1).$promise.then(function (newData) { vm.totalCount = newData.total_count; vm.firstPage--; gridApi.infiniteScroll.saveScrollPercentage(); vm.data = newData.concat(vm.data); gridApi.infiniteScroll.dataLoaded(vm.firstPage > 1, vm.lastPage < Math.floor(newData.total_count / vm.pageSize) + 1) .then(vm.checkDataLength.bind(vm, 'down')); }); }, checkDataLength : function (direction) { var vm = this; if (vm.lastPage - vm.firstPage > vm.keepPages) { if (direction === 'up') { vm.data = vm.data.slice(vm.pageSize); vm.firstPage++; vm.$timeout(function () { vm.gridApi.infiniteScroll.dataRemovedTop(vm.firstPage > 1, vm.lastPage < Math.floor(vm.totalCount / vm.pageSize) + 1); }); } else { vm.data = vm.data.slice(0, vm.pageSize * vm.keepPages); vm.lastPage--; vm.$timeout(function () { vm.gridApi.infiniteScroll.dataRemovedBottom(vm.firstPage > 1, vm.lastPage < Math.floor(vm.totalCount / vm.pageSize) + 1); }); } } }, deleteRow : function (rowId) { var vm = this, row = vm.$filter('filter')(vm.data, {_id: rowId})[0], rowIdx = vm.data.indexOf(row); vm.Entity.delete({id: rowId}).$promise.then(function () { vm.data.splice(rowIdx, 1); vm.toastr.success("Record successfully deleted!", "Success", {extendedTimeOut: 1500, timeOut: 1500}); }, function (data, status) { if (status !== 401) { vm.toastr.error(data.data.message); } }); } }; return InfiniteGrid; });
Inherited controller code
angular.module('myApp') .controller('SomeGridCtrl', ['$scope', '$timeout', '$resource', 'toastr', '$filter', '$routeParams', SomeGridCtrl]); function SomeGridCtrl($scope, $timeout, $resource, toastr, $filter, $routeParams) { var vm = this; $scope.vm = vm; vm.$scope = $scope; vm.toastr = toastr; vm.$filter = $filter; vm.$timeout = $timeout; vm.$resource = $resource; vm.$routeParams = $routeParams; // Call the parent constructor infiniteGrid.call(vm); } // Inherit the prototype SomeGridCtrl.prototype = Object.create(infiniteGrid.prototype); SomeGridCtrl.prototype.init = function() { var vm = this; vm.Entity = vm.$resource('/api/item/:id'); vm.columnDefs = [ { displayName: "Title" ,field: "title" //,filter: 'text', ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/card/{{ row.entity._id }}" ng-bind="COL_FIELD"></a></div>' },{ displayName: "URL" ,field: "url" ,filter: 'text' ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/card/{{ row.entity._id }}" ng-bind="COL_FIELD"></a></div>' },{ displayName: "Partner" ,field: "partner.fullName" //,filter: 'text' },{ field: 'review_count' ,displayName: 'Reviews' ,width: 80 ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/card/{{ row.entity._id }}/reviews" ng-bind="COL_FIELD"></a></div>' },{ displayName: "Created on" ,field: 'created' ,cellFilter: 'amCalendar' ,filter: false },{ displayName: "Delete" ,field: "dummy" //,width: 80 ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-click="grid.appScope.vm.deleteRow(row.entity._id)" confirm="Are you sure?" class="btn btn-xs btn-danger">Delete</a></div>' } ]; };
这篇关于对于多个视图Angularjs控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!