How can I run a controller without opening the view?

2

I am working with AngularMaterial specifically with $mdDialog when I enter the dialog my controller works, now what I need is to be able to run the controller without opening the view of the dialog. this is the function that contains the mdDialog

 vm.showAdvanced = function (ev, rowEmployee) {
        $mdDialog.show({
            controller: DialogController,
            templateUrl: 'dialog-liqui.tmpl.html',
            parent: angular.element(document.body),
            targetEvent: ev,
            clickOutsideToClose: true,
            fullscreen: true,
            locals: {
                employee: employee
            }
};

How can I run the controller and pass it on the locals data?

    
asked by Luis Ruiz Figueroa 28.09.2017 в 20:27
source

1 answer

2

You can achieve this by using the $rootScope and $controller services.

$rootScope to create a new scope for the controller you want to execute and the $controller for it to inject the services that the controller demands:

angular.module("app",[])
.controller("Ctrl1", function($scope, $rootScope, $controller){
  $scope.mensaje = "Precioname!";
  $scope.cargarCtrl = function(){
     // le asignamos un nuevo scope
     var $ctrlNewScope = $rootScope.$new();
     
     // le asignamos el locals al nuevo scope
     $ctrlNewScope.employee = {nombre: "einer" };
     
     // ejecutamos el controllador 
     $controller(DialogController,{ $scope : $ctrlNewScope });
  }
});

function DialogController($scope, $timeout){

  console.log("eejecutando segundo controllador!");
  console.log("el valor del emeployee es :"); 
  console.log($scope.employee);
  $timeout(function(){
    console.log("el controlador esta injectando los servicios perfectamente!");
  },2000);
  
  
}
<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="cargarCtrl()">{{mensaje}}</button>
 </div>
</div>

I do not know why you want to just initialize a driver without any view when you can use a service but that would be your decision.

    
answered by 28.09.2017 / 21:51
source