Sam
Sam

Reputation: 124

Directive does not link from controller($scope) after updating from 1.2.x

I have made a directive that helps me reduce the number of dependencies I need to inject into a main application controller by injecting them into isolated directives.

For instance, I have a drop list of genders ["MALE, "FEMALE"]. I have registered this array as a value provider. This is a simple example of a directive that functions in AngularJS 1.2.28

Directive:

module.directive('appGenderOptions', ['genders', function(genders) {
  return {
    restrict: 'A',
    require: 'ngModel',
    controller: function($scope) {
      $scope.genders = genders;
    },
    compile: function(elem, attr) {
      attr.ngOptions = 'g for g in genders';
    }
  };
}]);

View:

<select ng-model="person.gender" app-gender-options></select>

So when this directive is linked, it adds the genders to the select list and binds to the model without having to inject genders into the main controller.

Having updated to the latest version 1.4.2, the genders are no longer appended to the select list. I suspect its related to the breaking changes made to the HTML compiler $compile in 1.3 and they way scope isolation now works, but admittedly I am a little stumped.

Could you please provide me some advise as to how I can repair this convenience directive?

Upvotes: 3

Views: 55

Answers (1)

scniro
scniro

Reputation: 16989

This is an odd issue and while reviewing the Migration docs, I couldn't quite get enough information on what was changed to point out what may have broke your 1.2 example. I'd be interested to find out though, in detail, but as a workaround for your issue, the following should solve it for you...

Note that I have injected the $compile service as you will see in the example

compile: function(elem, attr) {
    elem.removeAttr('app-gender-options'); // necessary to avoid infinite compile loop
    elem.attr('ng-options', 'g for g in genders');
    return function(scope) {
        $compile(elem)(scope);
    };
}

JSFiddle Link - working example

Upvotes: 1

Related Questions