[英]Reuse AngularJS controller logic
This is the code of one controller from my application, in the User page. 这是我的应用程序中“用户”页面中一个控制器的代码。
app.controller('UserCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/Users/GetUsers').success(function (data) {
$scope.data = data;
});
this.search = function () {
$http.post('/Users/SearchUser', $scope.search).success(function (data) {
$scope.data = data;
});
}
this.delete = function() {....}
}]);
On another page, the Permission page, I create a controller with the same logic 在另一页“权限”页面上,我创建了具有相同逻辑的控制器
app.controller('PerCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/Permission/GetPermissions').success(function (data) {
$scope.data= data;
});
this.search = function () {
$http.post('/Permission/SearchPermission', $scope.search).success(function (data) {
$scope.data = data;
});
}
this.delete = function() {....}
}]);
As you can see, the only different is the URL. 如您所见,唯一的不同是URL。 How can I reuse the logic from a controller to another?
如何将逻辑从一个控制器重用到另一个控制器?
That is exactly what services are for. 这正是服务的目的。
So instead of: 所以代替:
$http.get('/Permission/GetPermissions').success(function (data) {
$scope.data= data;
});
You'd call something like: 您会这样称呼:
permissionsService.get().then(function (data) {
$scope.data= data;
});
And: 和:
this.search = function () {
$http.post('/Permission/SearchPermission', $scope.search).success(function (data) {
$scope.data = data;
});
}
Replaced with something like: 替换为:
this.search = function () {
searchService.search().then(function (data) {
$scope.data = data;
});
}
etc... 等等...
Generally, all server calls should be in services anyway, so there's a great opportunity to improve your code and learn how to do it right. 通常,所有服务器调用无论如何都应该在服务中,因此有很大的机会来改进您的代码并学习如何正确执行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.