IE 8 下 angular 动态生成的 select 的兼容指令

发布时间:2019-07-14 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了IE 8 下 angular 动态生成的 select 的兼容指令脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

我们用的是 Angular 1.2.5,以下代码也只用此版本测试过。

angular 渲 select 有很多坑,例如:官方推荐是用 ng-options,但是这样渲出来的下拉菜单在某些版本的 chrome 上是不可用的,所以为了兼容,我们舍弃了 ng-options。那么只剩下 ng-rePEat 来渲下拉菜单,这样在 ie 8 下也是有坑的,对于动态生成的下拉菜单,ie 8 总是无法渲出各个 options,如图:

图片描述

图片描述

这种情况下就需要使用指令做点兼容,如下

<!-- 写出此等代码,只为方便,还望海涵 -->
<div class="pure-g mt" ng-repeat="courseTeacher in ctrl.newCourseTeacherList track by $index">
    <select ng-model="ctrl.newCourseTeacherList[$index]" ie-select-fix="ctrl.teacherList">
        <option ng-repeat="teacher in ctrl.teacherList track by teacher.id" value="{{teacher.id}}" ng-bind="teacher.name"></option>
    </select>
</div>

// ieSelectFix directive
app.directive('ieSelectFix', [
    '$document',

    function ($document) {

        return {
            restrict: 'A',
            require : 'ngModel',
            link    : function (scope, element, attributes) {
                var isIE = $document[0] &amp;& $document[0].attachEvent;
                if (!isIE) return;

                var $ele = element[0];
                //to fix IE8 issue with parent and detail controller, we need to depend on the parent controller
                scope.$watch(attributes.ieSelectFix, function () {
                    // setTimeout is needed starting from angular 1.3+
                    setTimeout(function () {
                        //this will add and remove the options to trigger the rendering in IE8
                        var oOption = new Option();
                        $ele.add(oOption);
                        $ele.remove($ele.options.children.length - 1);
                    }, 0);
                });
            }
        }
    }
]);

</script>

脚本宝典总结

以上是脚本宝典为你收集整理的IE 8 下 angular 动态生成的 select 的兼容指令全部内容,希望文章能够帮你解决IE 8 下 angular 动态生成的 select 的兼容指令所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。