优化角度指令中的代码

时间:2016-11-14 04:36:58

标签: angularjs angularjs-directive

在angular directive init函数中,我声明常量并在html中使用常量。我有多个指令使用相同的常量我想保持常量是可重用的。 在下面的例子中,我在test和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;
}
}});

1 个答案:

答案 0 :(得分:0)

您可以使用AngularJS中的$provider.constant方法创建DRY常量:

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

您可以将EXAMPLE_CONSTANT注入任何模块,作为依赖项

相关问题