2015-02-23 66 views
1

我有點擔心,如果我問一個noob問題,或者如果它是一個JavaScript功能,我一直沒能找到很多,儘管谷歌搜索

我增加了的簡單的指令編程使用$編譯和所有工作正常。

我的問題是這條線

var el = $compile(newElement)($scope); 

如何雙括號工作/他們在做什麼?完整的代碼以供參考,但它只是我不確定的括號。

var myApp = angular.module('myApp', []); 

myApp.directive('myDirective', function() { 
    return { 
     template: 'Hello', 
     restrict: 'E' 
    } 
}); 

myApp.controller('mainController', [ 
    '$scope', '$compile', function($scope, $compile) { 

     $scope.addDirective = function() { 
      var newElement = angular.element(document.createElement('my-directive')); 
      var el = $compile(newElement)($scope); 
      angular.element(document.body).append(el); 
     }; 
    } 
]); 
+0

這不是任何先進的功能。 '$ compile(newElement)'返回一個函數。然後使用第二組parens立即用'$ scope'調用該函數。 – aarosil 2015-02-23 20:31:01

回答

1

$compile返回另一個函數。你可以做類似的事情:

function foo(greeting) { 
    return function(target) { console.log(greeting, target) }; 
} 

foo('Hello, ')('world'); 
+0

謝謝,現在有道理:) – 2015-02-23 20:41:43

1

正如你已經知道javascript中的括號是一個函數調用操作符(也是分組)。換句話說,用()運算符可以調用一個函數。從這裏很明顯,代碼

$compile(newElement)($scope); 

意味着$compile(newElement)這一結果是功能,因此它可以被執行。這個返回的函數接受一個參數 - 一個範圍對象,在該範圍對象中編譯上下文新的DOM元素。

1

$compile(tElement, tAttrs, transclude)返回指令link:(後鏈接)功能。

app.directive('exampleDirective', [function() { 
    return { 
     restrict: 'A', 
     scope: { value: '=value'}, 
     template: template, 
     link: function (scope, element, attr) { 

      scope.count = 0; 
      scope.increment = function() { 
       scope.value++; 
      }; 

     } 
    }; 
}]); 

在這種情況下,$compile('<div example-directive></div>');將返回link:功能,這樣你就可以帶參數(如scope第一)調用它,並且實例化上下文。

1

這都是調用函數的標準JavaScript語法。可能會令人困惑的是$compile是一個返回函數的函數。所以

$compile(newElement) 

本身的功能,並且可以被稱爲像任何其他功能,這是寫

$compile(newElement)($scope); 

時,如果你願意,你可以打破這種成單獨的線,這可能使它發生了什麼更清晰:

var linkFunction = $compile(newElement); 
linkFunction($scope); 

您可以參考usage of $compile in the docs。作爲一個便箋,我會直接使用$compile:你可能會過於複雜的事情,並可能有更簡單的替代品(我曾經使用過它很少見)。