Selected AngularJS plugin selected: updated does not work, works in browser

I have included the selected plugin in my angularjs application. My app.js is as follows.

myApp.directive('chosen', function() { var linker = function (scope, element, attr) { scope.$watch('countriesList', function() { $('#countries').trigger('chosen:updated'); console.log('I acctuallty get in here'); }) element.chosen(); }; return { restrict: 'A', link: linker }; }) 

my choice is as follows

 <div class="control-group"> <label for ="countries" class="control-label">Countries: </label> <div class="controls"> <select chosen ng-model="countries" id="countries" ng-options="country.name for country in countriesList" data-placeholder="Select Countries" multiple class="span chzn-select"></select> </div> </div> 

The problem is that when the page is first loaded, nothing is displayed. Options are available when checking an item.

chosen:updated just doesn't work. I put console.log() in the clock and shot. If I run .trigger('chosen:updated') in a browser, it works fine. I tried element.trigger , but that didn't work either. Disappointment!

+5
source share
1 answer

You must let Angular (well, the browser itself) display the selection correctly before chosen . You can do this using setTimeout or Angular $timeout .

 app.directive('chosen', function($timeout) { var linker = function(scope, element, attr) { $timeout(function () { element.chosen(); }, 0, false); }; return { restrict: 'A', link: linker }; }); 

The third argument to false prevents an unnecessary digest loop.

Demo: http://plnkr.co/edit/9Afq65uatTjnb4J6ICcB?p=preview

If you need to dynamically add or remove elements, this will work:

 app.directive('chosen', function($timeout) { var linker = function(scope, element, attr) { scope.$watch('countriesList', function() { $timeout(function() { element.trigger('chosen:updated'); }, 0, false); }, true); $timeout(function() { element.chosen(); }, 0, false); }; return { restrict: 'A', link: linker }; }); 

Demo: http://plnkr.co/edit/rEBu6d3HtaNhThWidB5h?p=preview

Note that, by default, $watch uses referential equality to determine whether to execute a listener or not. If you add an element to the array, the countriesList variable will still refer to the same array, so the listener will not execute.

The third argument true , passed to $watch , allows angular.equals to be used instead of referential equality.

+8
source

Source: https://habr.com/ru/post/1211375/


All Articles