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

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

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

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

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

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

<!-- 写出此等代码,只为方便,还望海涵 -->
<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] && $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>
    原文作者:Doyle
    原文地址: https://segmentfault.com/a/1190000007345642
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞