Home select not initializing on filtered list
Reply: 1

select not initializing on filtered list

godskook
1#
godskook Published in 2018-01-12 16:21:39Z

The following piece of code works, except for one issue, the UI's drop-down doesn't initialize to the contents of the model. The model is correctly initialized, the cookies are correctly saved/loaded. And the rest of the code has been working just fine for a while. I'm at a loss as to why the select won't initialize.

app.controller("thisController",
    function ($scope, $http, $log, $rootScope, $location, $uibModal, $cookies) {
    
    $scope.saveCookie = function (key, value) {
        $cookies.putObject(key, value);
    }
    $scope.getCookie = function (key) {
        return $cookies.getObject(key);
    }
}
    <select class="form-control"
            id="yearDropdown"
            ng-model="selectedYear"
            ng-init="selectedYear=getCookie('selectedYear')"
            ng-change="saveCookie('selectedYear', selectedYear)"
            ng-options="contract.ContractYear for contract in contractList
                      | orderBy:'ContractYear'
                      | unique:'ContractYear'">
        <option value="">All years</option>
    </select>

https://imgur.com/a/fsir4

Nikolaj Dam Larsen
2#
Nikolaj Dam Larsen Reply to 2018-01-12 18:01:34Z

The reason the <select>-element isn't initialized with the value loaded from the cookie, is because it attempts to match the object reference of the initialized object, with the references to the contract objects in your contractList-variable. Since the initialized object comes from a cookie, it object reference doesn't match any of the objects in the contractList.

To solve this, you can specify to the ngOptions-directive, which attribute it should use to match objects to each other. You do this by appending track by [expr] to the expression.

So to fix your issue, your template should look somewhat like this:

<select class="form-control"
        id="yearDropdown"
        ng-model="selectedYear"
        ng-init="selectedYear=getCookie('selectedYear')"
        ng-change="saveCookie('selectedYear', selectedYear)"
        ng-options="contract.ContractYear for contract in contractList
                  | orderBy:'ContractYear'
                  | unique:'ContractYear'
                  track by contract.ContractYear">
    <option value="">All years</option>
</select>

If you have some other unique identifier on the contract-object (an id for instance), you should naturally opt to track by that instead.

Note: I strongly recommend moving the ngInit logic to your controller.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307342 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO