How to use a controller function in another ANGUALRJS controller

1

I am doing a REST where I try to call in a function, a function of another controller, but with $parent I do not show the function in the console nor with $scope , the function that I try to call is this $scope.getInsuranceRequests(); :

$scope.example = function() {
    $http.get(root + 'ruta/url', {
            params: id
        }).then(function(res) {
            if (res.status === 200) {
                Dialogs.infoToast("Correo enviado correctamente");              
                $scope.getInsuranceRequests();
            }
        }
}


I'm trying with this

angular.extend(this, $controller('OtroControladorQueTieneLafuncionQueNecesito', {
       $scope: $scope 
    }));
    
asked by zerokira 19.12.2017 в 21:06
source

1 answer

3

You should not initialize a controller just to get the reference to a function, since you would be doing too much work and initializing unnecessary objects.

Enclose your function in service and inject it into all the drivers you need. For example:

angular.module("app",[])
.service("insuranceService",function(){
  this.getInsuranceRequests = function(){
    console.log("obteniendo los insurrance");
  }
  
})
.controller("ctrl1",function($scope, insuranceService)
{
   $scope.mostrarValor = function() {
    insuranceService.getInsuranceRequests()
   }
})
.controller("ctrl2",function($scope, insuranceService)
{
   $scope.mostrarValor = function() {
    insuranceService.getInsuranceRequests()
   }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" >
  <div ng-controller="ctrl1">
    <button ng-click="mostrarValor()">Mostrar valor</button>
  </div>
   <div ng-controller="ctrl2">
    <button ng-click="mostrarValor()">Mostrar valor</button>
  </div>
</div>
    
answered by 19.12.2017 в 21:16