2014-06-25 60 views
1

這只是關於Angular指令的一般問題。爲什麼角度選擇具有返回對象的函數,而不是直接將對象列爲第二個參數?Angular指令的第二個參數,它爲什麼是一個函數?

換句話說,它爲什麼是這樣的:

app.directive('helloWorld', function() { 
    return { 
    restrict: 'AE', 
    replace: 'true', 
    template: '<h3>Hello World!!</h3>' 
    }; 
}); 

,而不是這樣的:

app.directive('helloWorld',{ 
    restrict: 'AE', 
    replace: 'true', 
    template: '<h3>Hello World!!</h3>' 
}); 

回答

5

這樣你就可以注入依賴

例如:

app.directive('helloWorld', function($rootScope) { 
    return { 
    restrict: 'AE', 
    replace: 'true', 
    template: '<h3>Hello World!!</h3>' 
    }; 
}); 

角將注入$ rootScope進入你的指令。

2

因爲當你實例化一個指令時你想要一個新的實例。該函數將爲您實例化一個新對象,而不是返回相同的對象。

另外該函數也可以用於依賴注入。

2

我相信這是爲了允許依賴注入ex。

.directive('someDirective', ['$filter', function ($filter) { 
    'use strict'; 

    return { 
     restrict: 'A', 
     require: 'ngModel', 
     link: function (scope, element, attrs, ngModel) { 

      }); 
     } 
    }; 
}]); 
相關問題