Myth
Myth

Reputation: 1602

Select does not auto update on ng-model change rendered using ng-repeat

I am creating dropdown in a directive as follows:

<select ng-model="selectedSite">
    <option value="new">Add New Site</option>
    <option value="line" disabled>------------------------</option>
    <option ng-repeat="site in defaultSites"
            value="{{$index}}">
        {{site.name}}
    </option>
 </select>

Directive is:

app.directive('siteForm', function() {
return{
    restrict: 'E',
    replace: true,
    scope: {
        site: '=',        
        defaultSites: '=',
        selectedSite: '=',

    },
    templateUrl: '/views/templates/site_form.html',
    link: function($scope, element, attrs) {

    $scope.$watch('selectedSite', function(newValue, oldValue) {
            console.log('Site selected:', newValue);
            if (newValue !== undefined && newValue !== null) {
                if (newValue !== "new") {
                    var value = $scope.defaultSites[parseInt(newValue)];
                    $scope.site.name = value.name;
                } else {
                    $scope.site.name = "";
                }
            }
        });
    }
};
});

However when I provide the initial index in selectedSite, it does not work and always shows first option. E.g. If we provide the selectedSite as "1" then option with value "1" should get selected which is not happening.

Everything else works fine including $watch and selectedSite gets populated when I select option from dropdown.

I am using AngularJS v1.2.10.

Upvotes: 2

Views: 781

Answers (2)

scs
scs

Reputation: 119

Try to use ng-selected in following way

<option ng-repeat="site in defaultSites" value="{{$index}}" ng-selected="{{$index == selectedSite}}">
        {{site.name}}
</option>

Upvotes: 4

reaxis
reaxis

Reputation: 1431

Try calling $scope.$apply() at the end of your $watch handler.

See the AngularJS docs on Scope.

Upvotes: 0

Related Questions