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

JavaScript/Angular borrowing a function and appending parameters

本文关键字:函数 一个 参数 Angular JavaScript      更新时间:2023-09-26

假设我有一个服务函数,它接受一个静态参数和第二个自定义参数,该参数根据它被注入的控制器而变化。我希望我的控制器/视图调用这个服务函数,而不需要在控制器本身中编写一个自定义方法来传递那个自定义参数。我不确定这种技术是否涉及套用、调用、绑定或应用。

.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');
  }
});

据我所知,您需要在视图中使用service,因此最简单的方法是将$scope变量设置为service:

$scope.service=$service;

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

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

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

我创建了一个匿名函数,它调用我们的调用(第二个调用是在调用函数的原型方法中构建的)方法,具有所需的参数。

但是如果你的服务在每个用法上都不同,更好的方法是在服务构造函数中返回。因此,我们可以每次都使用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>  

所以我们可以通过创建新对象以不同的方式使用我们的服务。