重用功能在angularJS两个不同comtrollers [英] Reuse function in two different comtrollers in angularJS

查看:201
本文介绍了重用功能在angularJS两个不同comtrollers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个不同的视图控制器,而使用相同的功能的其范围的的,例如内设置一些作用域变量,像这样:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆