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

咱们用的是 angular 1.2.5,如下代码也只用此版本测试过。chrome

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

图片描述

图片描述

这种状况下就须要使用指令作点兼容,以下测试

<!-- 写出此等代码,只为方便,还望海涵 -->
<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>
相关文章
相关标签/搜索