2017-06-06 73 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:...} –

相關問題