在AngularJS指令中以编程方式选择Select box的空白选项

Select the blank option of select box programmatically in AngularJS directive

本文关键字:box Select 空白 选项 选择 方式 指令 AngularJS 编程      更新时间:2023-09-26

我有一个选择框,其中有一个空白选项和一些其他选项。这些选项不是用ngOptions指令生成的,因为它们是在服务器端(用Symfony表单)生成的。

在某些情况下,我想取消选择框的选定值。以便选中空白选项。但我做不到。选择框没有更新。

我创建了一个jsfiddle来显示这个问题。

<div ng-controller="MyCtrl">
    <form name="form">
        <select ng-model="foo.hero" name="foo[hero]" my-directive="">
            <option value=""></option>
            <option value="1">Batman</option>
            <option value="2">Superman</option>
            <option value="3">Spiderman</option>
        </select>
    </form>
    <p>Selected: {{ foo.hero }}</p>
</div>
javascript

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

在调用$setViewValue后使用modelController.$render()。这将更新DOM元素。

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();
            });
        }
    };
});

此处更新小提琴

这样做:

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

,因为你选择的模型是foo。

不确定为什么需要与modelController打交道?你就不能把模型更新为默认值吗?

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

此处更新小提琴