Hi guys, I’m having problems in my angular application with select2, in my login page, I put a select2 to test, using multiple, but when logging in, on any other page of the application select2 does not work anymore, below images and excerpts from code.
In an Angular app, the contents of each page are loaded dynamically by the router when the user navigates to that page. Therefore, the select2 widget on the login page is a different widget than the one on the application page. My guess is that your select2 initialization code (shown in O.js) only runs once, rather than on each page transition.
There are several ways to accomplish this, but I recommend one of the following:
- (The easier way:) Initialize the select2 widget in the controller for your application’s page (and in the controllers for any other pages that contain a select2 widget),
- Or (the more the “Angular” way:) create a custom directive that implements the select2 widget and performs the widget initialization in the directive’s
linkcallback, and use that directive on every application page where you need the widget.
If you take this approach you’ll need to embed your widget initialization code in a
scope.$apply()callback, because the widget initialization will alter the DOM, and Angular needs to know about that. And to ensure the
$apply()doesn’t run during an already running
$digestcycle, you’ll need to either embed it in a
$timeout()callback (you can use a delay of 0) to ensure the
$apply()runs on the next
$digestcycle. Alternatively, you can use
scope.$applyAsync()and skip the
$timeout()call altogether. Here’s some more info about this pattern: https://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm