简体   繁体   English

在两个不同的控制器AngularJS中使用相同的功能

[英]Using same functions in 2 different controllers AngularJS

I am trying to reuse a few bigger functions over 3 controllers in Angular JS. 我试图在Angular JS中重用3个控制器上的一些更大的功能。 I don't want to pin the functions to my root scope as I want to keep it clear of functions which will be used only 3 times within those 3 controllers. 我不想将函数固定到我的根作用域,因为我想要清除那些在这3个控制器中仅使用3次的函数。

    angular.module('adminModule', ['adminDependency'])

        .controller('ctrl1', ['$scope', 'details', function ($scope, details) {
            // use functions
        }])

        .controller('ctrl2', ['$scope', 'details', function ($scope, details) {
            // use functions
        }])

        .controller('ctrl3', ['$scope', 'details', function ($scope, details) {
            // use functions
        }])

Can you tell me how i can achieve that without writing my functions into the root scope? 你能告诉我如何在不将我的功能写入根范围的情况下实现这一目标吗?

Tried it inside a factory but calling AdminModule.toLevelKey() wont work... 在工厂里尝试但是调用AdminModule.toLevelKey()不会工作......

    .factory('AdminModule',
        [ '$resource', 'serviceURL', function ($resource, serviceURL) {

            return $resource(serviceURL + 'class/:id', {
                    id : '@id'
                }, {
                    getClasses : {
                        method  : 'GET',
                        url     : serviceURL + 'extended/class',
                        isArray : true
                    },

                    toLevelKey : function (value) {
                        var return_key = parseInt(Math.floor(value / 3));
                        var return_level = value % 3;

                        return { level : return_level + 1, levelTranslationKey : return_key + 1 };
                    },

                    fromLevelKey : function (level, key) {
                        if (angular.isDefined(level)) {
                            var value = (key - 1) * 3 + (level - 1);

                            return value;
                        } else {
                            return null;
                        }
                    }
                }
            );
        } ]);

This can be done by a service: 这可以通过服务来完成:

.service('myService', function(){
   return {
      fn: function(){
        // do what you want
      }
   }
});

usage: 用法:

.controller('ctrl2', ['$scope', 'details', 'myService', 
             function ($scope, details, myService) {
   // use functions
   myService.fn();
}])

In accordance with the above comment of David Fariña: "Are there even more options?". 根据DavidFariña的上述评论:“还有更多的选择吗?”。

Except executing, you also can pass data from one controller to another and broadcast event, when it happens. 除了执行之外,您还可以将数据从一个控制器传递到另一个控制器并在事件发生时广播事件。

SharedService: SharedService:

    angular.module("yourAppName", []).factory("mySharedService", function($rootScope){

        var mySharedService = {};

        mySharedService.values = {};

        mySharedService.setValues = function(params){
            mySharedService.values = params;
            $rootScope.$broadcast('dataPassed');
        }

        return mySharedService; 
   });

FirstController: FirstController:

 function FirstCtrl($scope, mySharedService) {
      $scope.passDataInSharedSevice = function(params){
         mySharedService.setValues(params);
      }
 }

SecondController: SecondController:

 function SecondController($scope, mySharedService) {
    $scope.$on('dataPassed', function () {
        $scope.newItems = mySharedService.values;
    });
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM