【问题标题】:Why does my function need parentheses?为什么我的函数需要括号?
【发布时间】:2017-11-07 04:58:43
【问题描述】:

在我的框架中,函数调用时不带括号......(参见 showErrors)

(function () {
  'use strict';

  angular
    .module('core')
    .directive('showErrors', showErrors);

  showErrors.$inject = ['$timeout', '$interpolate'];

  function showErrors($timeout, $interpolate) {
    var directive = {
      restrict: 'A',
      require: '^form',
      compile: compile
    };

    return directive;

我知道它是如何工作的......但是当我尝试这个时,我的组件将无法工作。仅当我将其更改为 .component('hotkeys', HotkeysComponent()); // 为 HotkeysComponent 添加括号

  angular
    .module('contacts.components')
    .component('hotkeys', HotkeysComponent);

  function HotkeysComponent() {
    var component = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      controller: 'AddManagerController',
      controllerAs: 'vm'
    };

    return component;

澄清一下,除非我执行 HotkeysComponent(),否则它不会起作用

angular
  .module('contacts.components')
  .component('hotkeys', HotkeysComponent()); // why don't the other functions need ()?

【问题讨论】:

    标签: angularjs components


    【解决方案1】:

    两者之间有很大的不同。 HotkeysComponent作为参数给出函数指针,而HotkeysComponent()HotkeysComponent返回的值。

    一个例子:

    testFunction(variable) {
        variable();
    }
    
    testFunction(alert);
    

    这里我们将 alert 作为函数(不是返回值)传递。现在我们可以在testFunction中执行这个函数了。

    testFunction(variable) {
        console.log(variable);
    }
    
    sum(x, y) {
        return x + y;
    }
    
    testFunction(sum(10,20));
    

    这里我们将 sum 函数的结果传递给函数,我们可以在 testFunction 中使用它。

    【讨论】:

    • 不是“返回指令”只是创建一个对象,例如 { templateUrl: ... }
    【解决方案2】:

    可以使用 AngularJS 模块的.component() 方法注册组件(由angular.module() 返回)。该方法有两个参数:

    • 组件的名称(字符串形式)。
    • 组件配置对象。 (请注意,不同于.directive() 方法,此方法不采用工厂函数。)

    根据您的问题,第二个参数必须是一个对象,并且仅在您调用函数时才会发生(第二个参数)

    Components in angular js 阅读本文了解更多信息

    【讨论】:

    • Mr_Perfect,我可以通过聊天问你几个后续问题吗?
    • 请先看文档,再问我。一切都会清楚地在那里
    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 2013-10-05
    • 2012-08-03
    • 2014-08-09
    • 1970-01-01
    • 2013-06-16
    • 2014-06-20
    • 2011-08-30
    相关资源
    最近更新 更多