JavaScript/Angular 借用函数并附加参数

JavaScript/Angular borrowing a function and appending parameters

假设我有一个服务函数,它采用静态参数和第二个自定义参数,该参数根据注入的控制器而变化。我希望我的 controller/view 调用此服务函数而无需编写控制器本身中的自定义方法只是为了传递该自定义参数。我不确定这种技术是否涉及柯里化、调用、绑定或应用。

.service('ExampleSvc', function() {
  this.call = function(param, controller) {
    console.debug(param, controller);
  }
})

.controller('FirstCtrl', function($scope, ExampleSvc) {
  $scope.call = ExampleSvc.call; // magic happens here

  // avoid writing below
  $scope.call = function() {
    ExampleSvc.call('param', 'FirstCtrl');
  }
});

.controller('SecondCtrl', function($scope, ExampleSvc) {
  $scope.call = ExampleSvc.call; // magic happens here

  // avoid writing below
  $scope.call = function() {
    ExampleSvc.call('param', 'SecondCtrl');
  }
});

据我了解您需要在视图中使用服务,最简单的方法是将 $scope 变量设置为服务:

$scope.service=$service;

因此,服务中的每个方法都可以直接从视图中调用,无需创建任何特殊的 $scope 方法。

如果只需要一个方法,我们需要改变它的参数:

$scope.call = function(){ ExampleSvc.call.call(this,'param', 'FirstCtrl'); };

我创建了匿名函数,它调用我们的 call(第二次调用是在调用函数的原型方法中构建的)方法。

但是如果您的服务在每次使用时都不同,更好的方法是在服务构造函数中 return。这样我们每次都可以使用new关键字,得到新的服务对象。

//服务代码

return function(controller){

  this.controller=controller;

  //here methods ...

};

//控制器代码

$scope.service=new service("ControllerName");

因此,在这种方法中,我们可以为每次使用提供不同的服务对象,因此它是典型的服务单例。我将尝试展示这种方法的示例:

var app=angular.module("app",[]);

app.controller("cont1",function($scope,person){

  $scope.p=new person("Tom","Hanks");
  
});

app.controller("cont2",function($scope,person){

  $scope.p=new person("Will","Smith");
   
});

//our service which returns constructor
app.service("person",function(){

  return function(name,surname){
    
    this.name=name;
    this.surname=surname;
    
    
    this.getName=function(){
    
      return this.name;
      
    };
    
    this.getSurname=function(){
    
      return this.surname;
    };
    
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  
  <div ng-controller="cont1">
  
      <span> Person is: <b>{{p.getName()}} {{p.getSurname()}}</b></span>
  </div>  
  
  <div ng-controller="cont2">
      <span> Person is: <b>{{p.getName()}} {{p.getSurname()}}</b></span>
  </div>  
  
  
</div>  

所以我们可以通过创建新对象以不同的方式使用我们的服务。将其发送到作用域可以直接在那里 运行 配置对象。