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] && $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>

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...