angularjs – 首先选择的元素在IE中不起作用

前端之家收集整理的这篇文章主要介绍了angularjs – 首先选择的元素在IE中不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我们使用带有select元素的ng-options指令时,我们在IE中看到一些非常奇怪的行为,当我们使用< option ng-repeat =''>时,这些行为不会发生.

我第一次从使用ng-options创建的下拉框中选择一个选项,无论我选择哪个选项,都会显示第一个选项.

如果我使用ng-repeat创建选项,它每次都能完美运行.

如果我从“损坏”下拉列表中选择一个选项,然后从未损坏的选项中选择一个选项,则第一个下拉框实际上会更改其选定项目以显示正确的选择.

我正在使用IE 11,并在此处举例说明了这个问题. http://jsfiddle.net/Q26mW/

解决方法

我已经制定了一个指令来解决这个问题……我称之为“空选”:

myApp.directive("emptyOption",["$timeout",function ($timeout) {
    return {
        restrict: "A",require: "^ngModel",link: function (scope,element,attrs,ngModelCtrl) {
            //Get "SELECT" element of empty option
            var parentSelectDom = element[0].parentNode,removed = false;

            //Make sure the element is "SELECT" before proceeding.
            if (parentSelectDom.nodeName === "SELECT") {

                //When $modelValue changes,either add/remove empty option
                //based on whether or not $modelValue is defined.
                scope.$watch(function () {
                    return ngModelCtrl.$modelValue;
                },function (newVal,oldVal) {
                    if (newVal === undefined) {
                        if (removed) {
                            $timeout(function () {
                                //Add empty option back to list.
                                parentSelectDom.add(element[0],parentSelectDom[0]);
                            },0);
                            removed = false;
                        }
                    }
                    else if (!removed) {
                        $timeout(function () {
                            //remove empty option.
                            parentSelectDom.remove(0);
                        },0);
                        removed = true;
                    }
                });
            }
        }
    }
}]);

该指令允许为select指定一个空选项.在进行选择时,它会删除该选项,并在清除模型值时添加空选项.

小提琴here.

猜你在找的Angularjs相关文章