Alex J Alex J - 7 months ago 94
Javascript Question

AngularJS: $decorator binding new variables to directive

I'm using a decorator to add a variable to the isolated scope of a directive. But somehow, it doesn't work and I tried almost everything.

The exactly directive is one of 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: '=?'
},
...
})


The $decorator code, which I use to change the template and add a new variable is:

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;
});
}]);


Then, in the I add:
index="$index"
and in the template I use it typing
{{index}}
, but always undefined...

Any suggestions? Thanks

Answer

Confirmed that this is a bug in Angular 1.3.x: https://github.com/angular/angular.js/issues/10149

The current workaround is to use .$$isolateBindings on the directive instead of .scope. Here's the workaround for your code:

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;
    });
}]);
Comments