重用功能在angularJS两个不同comtrollers [英] Reuse function in two different comtrollers in angularJS
问题描述
假设我有两个不同的视图控制器,而使用相同的功能的其范围的的,例如内设置一些作用域变量,像这样:
Suppose I have two different view controllers, whereas both use the same function within their scopes, e.g. set some scope variable, something like this:
View1Cntr.js
View1Cntr.js
app.controller('View1Cntr', ['$scope', function($scope) {
$scope.coloredContent = []; // default
// View1Cntr custom code here
$scope.clearColoredContent = function() {
$scope.coloredContent = [];
}
}]);
View2Cntr.js
View2Cntr.js
app.controller('View2Cntr', ['$scope', function($scope) {
$scope.coloredContent = []; // default
// View2Cntr custom code here
$scope.clearColoredContent = function() {
$scope.coloredContent = [];
}
}]);
有什么办法我只能定义一次函数并将它传递给两个控制器,使维护变得更加容易?
Is there any way I could only define the function once and pass it to both controllers, so that the maintenance becomes easier?
我想,这是一个封闭的情况下(请纠正我,如果我错了),这就是为什么我不知道怎么去解决它。
I guess, this is a closure case (please, correct me if I am wrong) and that is why I am not sure how to get around it.
谢谢!
推荐答案
您可以创建工厂,拥有一些方法,比如clearColoredContent注入这家工厂在两个控制器,并通过必要的范围,这一点。
you could create factory, with some method, like clearColoredContent inject this factory in both controller, and pass needed scope, to this.
app.factory('Utility', function(){
return {
clearColoredContent: function(scope){
scope.coloredContent = [];
}
}
})
和使用它像这样
app.controller('View2Cntr', ['$scope','Utility' , function($scope,Utility) {
$scope.coloredContent = []; // default
// View2Cntr custom code here
$scope.clearColoredContent = function() {
Utility.clearColoredContent($scope);
}
}]);
或者你也可以效用函数里使用这个
,和简单的指定这个效用函数为$范围
Or you can use inside Utility function this
, and simple assign this utility function to $scope
app.factory('Utility', function(){
return {
clearColoredContent: function(){
this.coloredContent = [];
}
}
})
app.controller('View2Cntr', ['$scope','Utility' , function($scope,Utility) {
$scope.coloredContent = []; // default
// View2Cntr custom code here
$scope.clearColoredContent = Utility.clearColoredContent;
}]);
这篇关于重用功能在angularJS两个不同comtrollers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!