使用服务和混淆使用['$ scope','service',function($ scope,service){}]在控制器之间传递数据

时间:2014-02-17 05:10:19

标签: javascript html5 angularjs controller angularjs-scope

我很难解决在angularJS中将数据从一个控制器传递到另一个控制器的问题。在我的代码出现之前:每当我点击templateController的div时,它会在ng-click的帮助下触发setTemplate ...现在我的目标是将templateController的所选数据发送到ReplyController ......

在这里阅读论坛帖子后,我决定创建一个名为“selectionService'”的服务,这样我就可以在2个控制器之间传输数据......

//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();
});

所以无论何时我运行此代码,我都会收到此错误

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

我再次调整了他们建议使用Squarebrackets并放入$ scope,servicename然后用相同参数编写函数的代码。我不明白为什么我应该这样做?事后做了一些改变之类的  [ '$scope' , 'service' , function($scope, service){}]

我仍然无法找到使用服务将数据从一个控制器传递到另一个控制器的解决方案。

你可以帮忙吗?我错过了什么?我对angularJS做事的方式很新。

1 个答案:

答案 0 :(得分:1)

我认为这实际上非常简单。您只需使用this.将您的方法添加到服务中即可。目前,他们在window上宣布。更改服务声明以使用this ...

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

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

至于使用数组符号表示依赖项,这是一个很好的做法,但并不是必需的。如果您通过缩小器运行代码,它将使您免于头痛。