【问题标题】:Select the blank option of select box programmatically in AngularJS directive在AngularJS指令中以编程方式选择选择框的空白选项
【发布时间】:2014-08-16 04:51:30
【问题描述】:

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

在某些情况下,我想取消选择选择框的选定值。以便选择空白选项。但我无法让它发挥作用。选择框不会更新。

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

html

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

【问题讨论】:

  • 并非如此。我的问题是,我必须更改指令中的选定值。
  • 好的,ng-init 不适合,因为该值稍后会发生变化?您需要在某个时候执行此操作 later? In that case I'd probably write an ng-timeout` 反映 ng-init 功能但将其包装在 $timeout 中...实际上@Delta 在下面执行...

标签: javascript angularjs angularjs-directive


【解决方案1】:

在调用 $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();
            });
        }
    };
});

更新小提琴here

【讨论】:

    【解决方案2】:

    这样做:

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

    由于您选择的模型是 foo.hero ,因此无论您何时更改它,该选择都会更改所选内容。

    【讨论】:

    • 但这并不会使表单变脏。
    【解决方案3】:

    不知道为什么要搞砸modelController?不能直接把模型更新成默认值吗?

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

    更新小提琴here

    【讨论】:

    • 但这并不会使表单变脏。
    • 没错,但您的问题并未说明这是一项要求!
    猜你喜欢
    • 2010-12-07
    • 1970-01-01
    • 2011-10-07
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多