如何重用一个控制器用于2个不同的视图? [英] How to reuse one controller for 2 different views?
问题描述
我已经定义了一个控制器,并将其应用于2个差异很小的视图.
I have defined one controller, and apply it to 2 views with small differences.
角度代码:
app.controller('MyCtrl', function($scope) {
$scope.canSave = false;
$scope.demo = {
files : [{
filename: 'aaa.html',
source: '<div>aaa</div>'
}, {
filename: 'bbb.html',
source: '<div>bbb</div>'
}]
}
$scope.newFile = function(file) {
$scope.demo.files.push(file);
}
$scope.$watch("demo.files", function(val) {
$scope.canSave = true;
}, true);
});
查看1:
<div ng-controller="MyCtrl"></div>
查看2:
<div ng-controller="MyCtrl"></div>
示例代码非常简单,但是我的真实项目中有很多代码和逻辑.
The sample code is very simple, but there are a lot of code and logic in my real project.
视图1和2具有几乎相同的功能,只是有一些区别,但是我确实需要在控制器中为它们中的每一个编写一些代码.
The View 1 and 2 have almost the same features, only with a few differences, but I do need to write some code for each of them in the controller.
我不想为它们创建2个不同的控制器,因为它们具有大多数相同的逻辑.我不想将逻辑移至服务以在两个控制器之间共享它,因为逻辑并不普遍地成为服务.
I don't want to create 2 different controllers for them, because they have most of same logic. I don't want to move the logic to a service to share it between the 2 controllers, because the logic is not that common to be a service.
还有其他方法吗?
推荐答案
在给定条件下,我可能会做类似的事情
Under the given conditions I might be doing something like
function MyCommonCtrl(type){
return function($scope, $http) {
$scope.x = 5;
if(type = 't1'){
$scope.domore = function(){
}
}
....
....
}
}
angular.module('ng').controller('Type1Ctrl', ['$scope', '$http', MyCommonCtrl('t1')]);
angular.module('ng').controller('Type2Ctrl', ['$scope', '$http', MyCommonCtrl('t2')]);
然后
<div ng-controller="Type1Ctrl"></div>
和
<div ng-controller="Type2Ctrl"></div>
这篇关于如何重用一个控制器用于2个不同的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!