最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using same functions in 2 different controllers AngularJS - Stack Overflow

programmeradmin3浏览0评论

I am trying to reuse a few bigger functions over 3 controllers in Angular JS. 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.

    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...

    .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;
                        }
                    }
                }
            );
        } ]);

I am trying to reuse a few bigger functions over 3 controllers in Angular JS. 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.

    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...

    .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;
                        }
                    }
                }
            );
        } ]);
Share Improve this question edited Feb 19, 2014 at 19:14 BenMorel 36.6k51 gold badges205 silver badges335 bronze badges asked Feb 12, 2014 at 10:10 David FariñaDavid Fariña 1,5942 gold badges19 silver badges32 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

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 ment of David Fariña: "Are there even more options?".

Except executing, you also can pass data from one controller to another and broadcast event, when it happens.

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:

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

SecondController:

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

评论列表(0)

  1. 暂无评论