David Bochenski
David Bochenski

Reputation: 309

Angular UI select2 with tags not working inside custom directive

Using the Angular UI Select2 directive, with tags defined on an input field. If the input is itself inside a custom directive, then it is not initialised correctly and the console gives an error:

query function not defined for Select2 tagging

I suspect this might be to do with the order in which the directives are compiled / linked vs when the select 2 function is called.

Maybe there is a simple workaround, perhaps using the compile function or a directive controller instead of a link function? Or maybe it is an issue with the Angular UI select2 directive.

I have made a plunker that displays the problem:

http://plnkr.co/edit/myE5wZ

So my question is - How do you get get select2 tags working from inside a custom Angular directive?

Upvotes: 3

Views: 4599

Answers (5)

Satabol
Satabol

Reputation: 86

I have this error too. My short solution:

<input type="hidden" 
       name="citizenship" 
       class="form-control input-sm col-sm-10" 
       style="width:500px" 
       multiple 
       ui-select2="params.options.citizenshipOptions"   
       ng-model="cvLang.content.citizenship"
       ng-repeat="a in [1]"
 />

ng-repeat="a in [1]" is a magical thing!!! It is not clear for me a logic of a context, but this is working. May be this can help?

Upvotes: 0

Andy
Andy

Reputation: 75

By using the controller function instead of the link function in the directive it's working. Example:

function myFunction() { 
  var dir = {};
  dir.scope = { myModel: '=' };
  dir.restrict = 'E';
  dir.templateUrl = 'myTemplate.html';
  dir.replace = true;
  dir.controller = function ($scope) {
    $scope.myVar = ...;
  };

  return dir;
};

Upvotes: 0

ProLoser
ProLoser

Reputation: 4616

I just encountered this today and summarily realized the fix:

PostLinking functions are executed in reverse order (deepest grandchild to greatest grandparent).

Put your custom modal's code (or anything that sets $scope data for use in its children) inside a PreLinking function. PreLinking functions go from parent to child, and all PreLinking functions are performed before the PostLinking functions.

Upvotes: 4

testing123
testing123

Reputation: 11447

I had a similar issue. Your solution works but IMHO I think an even better solution is to use the controller function instead of the link function inside the directive. Doing this you do need nested directives.

Upvotes: 0

David Bochenski
David Bochenski

Reputation: 309

In the end I managed to find a solution I was happy with involving nesting two directives, that way the logic can be encapsulated inside the parent directive (not spilling out into the controller).

A Plunker of my solution is here for anyone who may stumble across the same issue:

http://plnkr.co/edit/ZxAPF5BzkgPtn9xddCRM

Upvotes: 5

Related Questions