2017-06-06 74 views
1

在我的框架,该功能被称为无括号....(见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()? 

回答

1

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

  • 组件的名称(以字符串形式)。
  • 组件配置对象。 (需要注意的是,不同的是.directive() 方法,这个方法并不需要一个工厂函数。)

根据您的问题,第二个参数必须是一个对象,只有当你调用的函数(第二个参数出现这种情况)

Components in angular js 阅读更多信息

+1

谢谢!所以这个对象是独一无二的组件在角.. –

+0

Mr_Perfect,我可以通过聊天问你几个跟进问题吗? –

+1

请先阅读文档,然后问我。一切都会在那里清楚 –

0

还有就是两者之间有很大的区别。 HotkeysComponent作为参数给出函数指针,而HotkeysComponent()是值HotkeysComponent的返回值。

一个例子:

testFunction(variable) { 
    variable(); 
} 

testFunction(alert); 

下面我们通过警报的功能(没有返回值)。现在我们可以在testFunction内执行这个功能。

testFunction(variable) { 
    console.log(variable); 
} 

sum(x, y) { 
    return x + y; 
} 

testFunction(sum(10,20)); 

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

+0

是不是 '返回指令' 只是让一个对象,如{templateUrl:...} –

相关问题