Passing data between controllers using service and

2019-09-01 09:29发布

问题:

I am badly stuck with this problem of passing data from one controller to other in angularJS. Before my code was: whenever I click on templateController's div, it would trigger setTemplate with the help of ng-click... Now my objective was to send templateController's selected data to ReplyController...

After reading forum posts here, i decided to create a service called 'selectionService', so that i can transmit data between 2 controllers...

//Defined Service

proApp.service('selectionService', function() {
  var selected_template;

  addTemplate = function(newObj) {
      selected_template = newObj;
  };
  getTemplate = function(){
      return selected_template;
  };
});

//Controller 1... where templates are selected

proApp.controller('TemplateController',function($scope, selectionService)
{
    $scope.templates = [ 
    {template_name:"Template 1", template_text:"We apologize for the interruption."} ,
    {template_name:"Template 2", template_text:"Thank you for contacting us."} ,
    } ,
    ];

    // on ng-click
    $scope.setTemplate = function(tmp)
    {
        selectionService.addTemplate(tmp);   
    }
});


// Controller 2 ... supposed to catch the selected template.

proApp.controller('ReplyController', function($scope, selectionService) 
{
    $scope.template = selectionService.getTemplate();
});

So whenever i run this code, i started getting this error

Object [object Object] has no method addTemplate...

Again I tweeked the code where they were suggesting to use Squarebrackets and put $scope , servicename and then write function with same parameters.. I don't understand why I should do this? Event after doing some changes like [ '$scope' , 'service' , function($scope, service){}] ,

I am still not able to figure out the solution to pass data from one controller to other using service.

Could you help? What am I missing? I am very new to angularJS way of doing stuff.

回答1:

I think it's actually quite simple. You just need to add your methods to the service by using this.. Currently they are declared on window. Change your service declaration to use this...

proApp.service('selectionService', function() {
  var selected_template;

  this.addTemplate = function(newObj) {
      selected_template = newObj;
  };
  this.getTemplate = function(){
      return selected_template;
  };
});

As for using the array notation for dependencies, it's a good practice but it's not required. It'll save you from headaches if you ever run your code through a minifier.