Angular 1.5将带参数的函数传递给组件?

car*_*ism 1 javascript angularjs

我有一个像下面这样的会话服务,有两种方法代表两种验证方式:

angular
  .module('myApp')
  .service('sessionService', SessionService);

function SessionService() {
  var $ctrl = this;

  this.logInTypeA = function(username, password, authenticator) {
    ...
  }

  this.logInTypeB = function(username, password, authenticator) {
    ...
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

我有一个登录表单组件.我想有两个表单实例使用两种不同的登录方法,但在其他方面是相同的:

<log-in-form log-in-method="$ctrl.sessionSerive.logInTypeA"></log-in-form>
<log-in-form log-in-method="$ctrl.sessionSerive.logInTypeB"></log-in-form>
Run Code Online (Sandbox Code Playgroud)

组件的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);
  };

  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行此命令时出现错误:

TypeError: Cannot use 'in' operator to search for '$ctrl' in testloginemail@example.com
Run Code Online (Sandbox Code Playgroud)

如何将服务中的方法传递给组件?

提前致谢.

小智 5

您的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>
Run Code Online (Sandbox Code Playgroud)

对于组件,您需要在参数周围添加花括号并添加每个参数名称:

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});
  };
  ...
}
Run Code Online (Sandbox Code Playgroud)