简体   繁体   English

如何在控制器之间共享功能?

[英]how do i share a function between controllers?

I am pretty new to angularjs and I want to know what is the best practice for this kind of problem. 我对angularjs很陌生,我想知道什么是解决此类问题的最佳实践。 I have a function in my controller1 used for validation of registration form which is called from my uniqueField directive which is attribute: 我的controller1有一个用于验证注册表单的函数,该函数从我的attribute属性的uniqueField指令中调用:

$scope.validation=function(param){
    $scope.loading[param.field]=true;

    var currentPath=$location.path(); //current route
    //function for ajax web call
    var webCall = $http({
               method: 'POST',
               url: currentPath+'/validation', 
               async : true,
               headers: {
                 'Content-Type': 'application/json'
               },
               timeout:10000,
               data: param});
    webCall.then(handleSuccess,handleError); //server call
    function handleSuccess(response) { //successful web call handler
      $scope.loaded[param.field]={};
      $scope.loading[param.field]=false;
      if(response.data.status===1) {
        $scope.loaded[param.field]["available"]=true;
        $scope.loaded[param.field]["error"]=false;
        $scope.loaded[param.field]["message"]=response.data.message;
      }
      else if(response.data.status===0){
        $scope.loaded[param.field]["available"]=false;
        $scope.loaded[param.field]["error"]=false;
        $scope.loaded[param.field]["message"]=response.data.message;
      }
    }
    function handleError(response){
      $scope.loaded[param.field]={};
      $scope.loading[param.field]=false;
      $scope.loaded[param.field]["error"]=true;
      $scope.loaded[param.field]["Message"]="Cannot fetch data from server";
    };
  }
}

Now I want similar functionality in next controller too. 现在,我也想在下一个控制器中使用类似的功能。 What would be the best practice so that I dont have to redefine the function again in another controller? 最好的做法是什么,这样我就不必在另一个控制器中重新定义功能了?

Services. 服务。

Controller is not the best fit to locate this type of logic, everything that is not DOM manipulation and logic should be encapsulated into services and then this dilema is solved. 控制器不是最适合定位这种类型的逻辑的,不是DOM操作和逻辑的所有内容都应该封装到服务中,然后解决这个难题。

Lets say you have 2 controller and a function called validate: 假设您有2个控制器和一个称为validate的函数:

Service: 服务:

angular('mymodule').factory('validateService', function() {
    var service = {
        validate: function() {
        //validation logic
        }
    }
    return service;
});

Ctrl 1: Ctrl 1:

angular('mymodule').controller('MyCtrl1',['$scope', 'validateService', function($scope, validateService) {
  $scope.validate = function() {
      validateService.validate();
  }  
}]);

Ctrl 2: Ctrl 2:

angular('mymodule').controller('MyCtrl2',['$scope', 'validateService', function($scope, validateService) {
  $scope.validate = function() {
      validateService.validate();
  }  
}]);

Use Scope Hierarchy 使用范围层次结构

If what you mean is you want to share the whole functionality (all used scope variables) between both of the controllers, just put the functionality on a closest common ancestor scope of both scopes. 如果您要表示的是要在两个控制器之间共享全部功能(所有使用的作用域变量),只需将功能放在两个作用域的最接近的共同祖先作用域上即可。 The easiest way to achieve this is by applying a controller on a closest common ancestor element in the DOM hierarchy. 实现此目的的最简单方法是在DOM层次结构中最接近的公共祖先元素上应用控制器。

Encapsulate the Functionality and Provide a Factory 封装功能并提供工厂

If what you mean is you need to share the functionality but have separate variables for each use, you want to encapsulate the functionality properly. 如果您的意思是需要共享功能,但每次使用都有单独的变量,则需要正确封装功能。 You can do this by creating a factory for your validation function: 您可以通过为验证功能创建工厂来做到这一点:

angular.module(...).value('createSomeValidator', function () {
    return function validate (param) {
        // instead of using separate variables, use properties of this function, like:
        // validate.loading[...] = ...;
    };
});

and the inject that factory into your controller and use it: 并将该工厂注入您的控制器并使用它:

angular.module(...).controller('...', ['createSomeValidator', function (createSomeValidator) {
    $scope.validateSomething = createSomeValidator();
}]);

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

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