How can I init default value for select2 with angularjs and $localStorage

158 Views Asked by At

I use select2, $localStorage and angularjs in my project, I want to get the value of my $localstorage as a default value but when I try this

$('.select').val($localStorage.f.tab.idSelect).trigger('change'); 

it doesn't work it doesn't show my default value I have the same issue for my select multiple

$('.selectSec').val($localStorage.f.tab.selectSecArray).trigger('change'); 

this is my .aspx file

<select class="form-control select">
    <option value="">---Please select---</option>
    <option ng-repeat="option in test" value="{{option.testid}}">{{option.testname}}</option>
</select>

<select class="form-control selectSec" name="secs[]" multiple="multiple">
    <option value="">---Please select---</option>
    <option ng-repeat="option in secs" value="{{option.secid}}">{{option.secname}}</option>
</select>

this is my app.js

app.controller('AppCtrl', function ($scope, $http, $localStorage) {
    $http.get("url1").then(function (response) {
        $scope.test= response.data.Liste
    })

    $http.get("url2").then(function (response) {
        $scope.secs= response.data.Liste
    })

    $('.select').val($localStorage.f.tab.idSelect).trigger('change');
    $('.selectSec').val($localStorage.f.tab.selectSecArray).trigger('change'); 

    jQuery(".select").change(function (e) {
        if (e.target.value == "")
            console.log("null")
        else
           $localStorage.f.tab.idSelect = e.target.value
   }) // I do the same for the multiple select
})

When do that it doesn't work but if I add this opt in my .select

Test nb 20

and I do this

$localStorage.f.tab.idSelect = 20
$('.select').val($localStorage.f.tab.idSelect).trigger('change'); 

It works perfectly so how can I make my select2 works with my angularjs and my $localstorage

0

There are 0 best solutions below