-2

I created a directive that should display a list of countries when it loads. It should "remember" the selected country when he user gets to the page again (after navigating inside the SPA). I am saving the selected country in a service, and when the page loads again, I get the country back from the service, and store it in "scope.country" var which is bound to the model of the select box, inside the directive.

template:

<select ng-model="country" ng-options="country.Name for country in data.countries" class="form-control">
    <option value="">Country</option>
</select>

Directive:

.directive('ggCountry', ["$http", function ($http) {
    return {
        templateUrl: '../../Common/js/angular/directives/templates/CountryDropDown.html',
        scope: {
            country: '=ngModel'
        },

        link: function (scope, element, attrs) {
            scope.data = {};
            scope.data.countries = [];
            $http.post("../Common/GetAllCountries", {}).then(function (answer) {
                scope.data.countries = answer.data.d;
                // select the country:
                if (scope.country != undefined) {
                    // using underscore library for the selection
                    scope.country = _.where(scope.data.countries, { Id: scope.country.Id });
                }
            });
        }
    };
}])

after selecting the country and setting it as the model of the select drop down list, i would expect that the view will change, and this country will be selected, but it doesn't act like that for some reason.

RoiTr
  • 136
  • 11

1 Answers1

0

Ok, that was stupid :)

I used the _.where(...) function, which returns an array, which can't be the model for a select drop down list.

To fix it, i changed the _.where() to _.findWhere() which returns the country object that CAN be bound to, and everything works perfectly.

RoiTr
  • 136
  • 11