godskook
godskook

Reputation: 144

select not initializing on filtered list

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://i.sstatic.net/OnMJw.jpg

Upvotes: 1

Views: 33

Answers (1)

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5674

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.

Upvotes: 1

Related Questions