Skip to content Skip to sidebar Skip to footer

Select The Blank Option Of Select Box Programmatically In Angularjs Directive

I have a select box with a blank option and some other options. The options are not generated with ngOptions directive, because they are generated on server side (with Symfony form

Solution 1:

Use modelController.$render() after you call $setViewValue. This will update the DOM element(s).

myApp.directive('myDirective', function($timeout) {
    return {
        require: ['ngModel', '?form'],
        link: function(scope, element, attrs, ctlrs) {
            $timeout(function() {
                var modelController = ctlrs[0];
                modelController.$setViewValue('');
                modelController.$render();
            });
        }
    };
});

Updated fiddle here.

Solution 2:

Do this:

$timeout(function() {
            scope.foo.hero = '';
        });

since the model of your select is foo.hero whenever you change it then the select will change the selected.

Solution 3:

Not sure why you need to muck around with modelController? Can't you just update the model to the default value?

myApp.directive('myDirective', function($timeout) {
    return {
        scope: {
            model: '=?ngModel'
        },
        link: function(scope, element, attrs, ctlrs) {
            $timeout(function() {
                scope.model = '';
            });
        }
    };
});

Updated fiddle here.

Post a Comment for "Select The Blank Option Of Select Box Programmatically In Angularjs Directive"