7

I'm trying to wrap a ui-select in a custom directive. (https://github.com/angular-ui/ui-select)

this.adminv2.directive('eventSelect', function() {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        ngModel: '=',
        placeholder: '='
      },
      controller: function($scope, $http) {
        return $scope.refreshEvents = function(searchTerm) {
          return $http.get('/events/autocomplete', {
            params: {
              term: searchTerm
            }
          }).then(function(response) {
            return $scope.events = response.data;
          });
        };
      },
      template: "<div>{{ngModel}}\n  <ui-select ng-model=\"ngModel\"\n             theme=\"bootstrap\"\n             ng-disabled=\"disabled\"\n             reset-search-input=\"false\">\n    <ui-select-match placeholder=\"Enter an event\">{{$select.selected.name}}</ui-select-match>\n    <ui-select-choices repeat=\"event in events track by $index\"\n             refresh=\"refreshEvents($select.search)\"\n             refresh-delay=\"0\">\n      <span ng-bind-html=\"event.name | highlight: $select.search\"></span>\n      <i class=\"icon-uniF111 fg type-{{raceType}} pull-right\" ng-repeat='raceType in event.racetypes'></i>\n      <br>\n      {{event.dates}} <i class='pull-right'>{{event.location}}</i>\n    </ui-select-choices>\n  </ui-select>\n</div>"
    };
  });

The select works properly, but the binding with ng-model doesn't work. I cannot set the model or read it. I don't get it since it works when I use a simple template such as

<div><input ng-model="ngModel"></div>

Is there something special to do because I wrap a directive in directive ?

1 Answer 1

13

I managed to make the binding work by setting the ng-model in the template as

ng-model="$parent.ngModel"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, I had been beating my head against this problem and your answer made it work for me too. Would you happen to know why this works?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.