Directive not bind to controller ($ scope) after upgrade from 1.2.x

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

For example, I have a genders dropdown ["MALE, "FEMALE"]

. I have registered this array as a valuable supplier. This is a simple example of a directive that functions inAngularJS 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 gender groups to the picklist and binds to the model without having to enter the gender groups into the main controller.

With the latest version 1.4.2 updated, gender groups are no longer added to the picklist. I suspect this is due to a violation of the changes made to the HTML compiler $compile

in 1.3 and they now expose scope isolation, but admittedly I'm a bit stumped.

Could you please provide me with some advice on how I can repair this handy directive?

+3


source to share


1 answer


This is a strange problem, and while looking through the Migration Docs , I couldn't get enough information about what was changed to indicate that your example 1.2 may have broken. I would be interested to know, though, in detail, but as a workaround for your problem, the following should solve it for you ...

Please note that I have introduced a service $compile

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

+1


source







All Articles