JavaScript/Angular借用一个函数并附加参数
JavaScript/Angular borrowing a function and appending parameters
假设我有一个服务函数,它接受一个静态参数和第二个自定义参数,该参数根据它被注入的控制器而变化。我希望我的控制器/视图调用这个服务函数,而不需要在控制器本身中编写一个自定义方法来传递那个自定义参数。我不确定这种技术是否涉及套用、调用、绑定或应用。
.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>
所以我们可以通过创建新对象以不同的方式使用我们的服务。
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 我可以在json对象中添加一个函数吗
- Javascript使函数一个接一个地执行
- 是JavaScript中的函数一个对象
- 两个几乎相等的jQuery函数;一个适用于IE,一个不适用于IE
- 两个Javascript函数一个window.onload=Custom.init;和一个window.onload=f
- 使javascript加载函数一个接一个地执行
- 如何通过两个嵌套的匿名函数(一个带有超时的事件处理程序)传递变量
- 为什么我不能让两个jQuery函数一个在另一个里面呢?
- 给函数一个变量名,而不是它的值
- 如何使用嵌入函数(一个滚动页由Pete - peachananr)
- 是否有可能给JavaScript函数一个类型/类?
- 确保两个函数一个接一个地执行,其中第一个函数内部有一个异步调用
- 两个不同的ajax函数一个接一个调用返回相同的值
- jQuery第一次更改函数一个工作
- 给这个函数一个id
- 如何给回调函数一个值一个变量在特定时刻
- 使用回调使两个函数一个接一个地运行
- 两个函数(一个用php)是否可以用“;onclick”;
- 两个几乎相同的函数.一个函数用Queue进行排队.Jquery效果在queued函数上不起作用.为什么