2016-11-14 69 views
1

在角度指令init函數中,我聲明常量並在html中使用常量。我有多個指令利用相同的常量,我想保持常量是可重用的。 在下面的例子中,我在測試和test1指令中都使用scope.sName和scope.sType,我如何將它放在公共位置並重新使用它。在角度指令中優化代碼

app.directive('test', function() { 
return { 
    restrict:'A', 
    scope: { someVal: '='} 
    link: function(scope, element, attrs) { 
    scope.sType = InvertoryConstant.serviceType; 
    scope.sName = InvertoryConstant.serviceName; 
} 
}}); 

app.directive('test1', function() { 
return { 
    restrict:'A', 
    scope: { someVal: '='} 
    link: function(scope, element, attrs) { 
    scope.sType = InvertoryConstant.serviceType; 
    scope.sName = InvertoryConstant.serviceName; 
} 
}}); 
+0

把普通代碼服務和將服務注入您的指令。 –

+0

是「InvertoryConstant」的一個對象,因爲它是一個常量,它的值在任何地方都不會改變? – Sravan

+0

現在你有哪些常數? – Sravan

回答

0

可以使用$provider.constant方法AngularJS創建DRY常數:

angular.module('projectApp', []) 
    .constant('EXAMPLE_CONSTANT','exampleConstant') 

你可以注入EXAMPLE_CONSTANT到任何您的模塊,作爲一個依賴