AngularJS:$ decorator将新变量绑定到指令

时间:2014-12-24 13:27:24

标签: javascript angularjs angular-ui

我正在使用装饰器将变量添加到指令的隔离范围。但不知何故,它不起作用,我几乎尝试了一切。

确切的指令是angular-ui:

之一
.directive('accordionGroup', function() {
  return {
    require:'^accordion',         // We need this directive to be inside an accordion
    restrict:'EA',
    transclude:true,              // It transcludes the contents of the directive into the template
    replace: true,                // The element containing the directive will be replaced with the template
    templateUrl:'template/accordion/accordion-group.html',
    scope: {
      heading: '@',               // Interpolate the heading attribute onto this scope
      isOpen: '=?',
      isDisabled: '=?'
    },
    ...
})

$ decorator代码,用于更改模板并添加新变量:

mainModule.config(['$provide', function ($provide){

    $provide.decorator('accordionGroupDirective', function($delegate) { 
          var directive = $delegate[0];
          directive.templateUrl = "views/parts/accordion-unit.html";
          angular.extend(directive.scope, { index:'@' });
          return $delegate;
    });
}]);

然后,在我添加:index="$index"并在模板中我使用它键入{{index}},但始终未定义...

有什么建议吗?感谢

1 个答案:

答案 0 :(得分:5)

确认这是Angular 1.3.x中的错误:https://github.com/angular/angular.js/issues/10149

目前的解决方法是在指令上使用.$$isolateBindings而不是.scope。这是代码的解决方法:

mainModule.config(['$provide', function ($provide){

    $provide.decorator('accordionGroupDirective', function($delegate) { 
          var directive = $delegate[0];
          directive.templateUrl = "views/parts/accordion-unit.html";
          directive.$$isolateBindings.index = {
              attrName: 'index',
              mode: '@',
              optional: true
          };
          return $delegate;
    });
}]);