如何将一个控制器重用于 2 个不同的视图? [英] How to reuse one controller for 2 different views?
问题描述
我定义了一个控制器,并将其应用于 2 个有细微差别的视图.
角度代码:
app.controller('MyCtrl', function($scope) {$scope.canSave = false;$scope.demo = {文件:[{文件名:'aaa.html',来源:'<div>aaa</div>'}, {文件名:'bbb.html',来源:'<div>bbb</div>'}]}$scope.newFile = 函数(文件){$scope.demo.files.push(file);}$scope.$watch("demo.files", function(val) {$scope.canSave = true;}, 真的);});
视图 1:
<div ng-controller="MyCtrl"></div>
视图 2:
<div ng-controller="MyCtrl"></div>
示例代码很简单,但是我的实际项目中代码和逻辑很多.
视图 1 和视图 2 具有几乎相同的功能,只有一些不同,但我确实需要在控制器中为它们中的每一个编写一些代码.
我不想为它们创建 2 个不同的控制器,因为它们具有大部分相同的逻辑.我不想将逻辑移动到服务以在 2 个控制器之间共享它,因为作为服务的逻辑并不常见.
还有其他方法吗?
在给定的条件下,我可能会做类似的事情
function MyCommonCtrl(type){返回函数($scope,$http){$scope.x = 5;如果(类型 = '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="Type2Ctrl"></div>
I have defined one controller, and apply it to 2 views with small differences.
Angular code:
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);
});
View 1:
<div ng-controller="MyCtrl"></div>
View 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.
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.
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.
Is there any other way to do it?
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')]);
Then
<div ng-controller="Type1Ctrl"></div>
and
<div ng-controller="Type2Ctrl"></div>
这篇关于如何将一个控制器重用于 2 个不同的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!