[英]Angular 1.5 passing a function with parameters to a component?
我有一个如下所示的会话服务,其中的两种方法代表两种身份验证方式:
angular
.module('myApp')
.service('sessionService', SessionService);
function SessionService() {
var $ctrl = this;
this.logInTypeA = function(username, password, authenticator) {
...
}
this.logInTypeB = function(username, password, authenticator) {
...
}
...
}
我有一个登录表单组件。 我想拥有两个使用两种不同登录方法的表单实例,但在其他方面相同:
<log-in-form log-in-method="$ctrl.sessionSerive.logInTypeA"></log-in-form>
<log-in-form log-in-method="$ctrl.sessionSerive.logInTypeB"></log-in-form>
该组件的JS看起来像这样:
angular
.module('myApp')
.component('logInForm', {
templateUrl: 'app/components/log-in-form.template.html',
controller: LogInFormController,
bindings: {
logInMethod: '&'
}
});
function LogInFormController() {
var $ctrl = this;
this.username = '';
this.password = '';
this.authenticator = '';
this.logIn = function() {
$ctrl.logInMethod($ctrl.username, $ctrl.password, $ctrl.authenticator);
};
...
}
但是,尝试运行此命令时出现错误:
TypeError: Cannot use 'in' operator to search for '$ctrl' in testloginemail@example.com
如何将服务中的方法传递给组件?
提前致谢。
您的HTML在服务名称中有一个错字。 这是我在Angular 1.4.x中执行的操作。
在HTML中,应该添加被调用函数的参数:
<log-in-form log-in-method="$ctrl.sessionService.logInTypeA(username, password, authenticator)"></log-in-form>
<log-in-form log-in-method="$ctrl.sessionService.logInTypeB(username, password, authenticator)"></log-in-form>
对于组件,您需要在参数周围添加花括号并添加每个参数名称:
angular
.module('myApp')
.component('logInForm', {
templateUrl: 'app/components/log-in-form.template.html',
controller: LogInFormController,
bindings: {
logInMethod: '&'
}
});
function LogInFormController() {
var $ctrl = this;
this.username = '';
this.password = '';
this.authenticator = '';
this.logIn = function() {
$ctrl.logInMethod({username: $ctrl.username,
password: $ctrl.password,
authenticator: $ctrl.authenticator});
};
...
}
如果您希望代码按名称使用服务功能:
<log-in-form log-in-method="logInTypeA"></log-in-form>
<log-in-form log-in-method="logInTypeB"></log-in-form>
使用属性@
绑定,然后将服务注入组件中:
app.component('logInForm', {
templateUrl: 'app/components/log-in-form.template.html',
controller: LogInFormController,
bindings: {
logInMethod: '@'
}
});
function LogInFormController(sessionService) {
var $ctrl = this;
this.username = '';
this.password = '';
this.authenticator = '';
this.logIn = function() {
var method = sessionService[$ctrl.logInMethod];
method($ctrl.username, $ctrl.password, $ctrl.authenticator);
};
...
}
使用属性访问方括号表示法通过名称选择所需的服务方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.