当我的项目在要求上进行了非常晚的更改以支持 IE9 时,我不想返回并注释我的所有<select>
元素或控制器来处理这个问题,所以我编写了以下指令来自动向所有元素或控制器添加行为:
angular.module('xxxxx')
.directive('select',
['$log', '$parse', '$timeout', function ($log, $parse, $timeout) {
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
return {
restrict: 'E',
scope: true,
require: ['select', '?ngModel'],
link: function (scope, elem, attrs, control) {
var isIE = document.attachEvent,
match;
if (isIE
&& attrs.ngOptions
&& (match = attrs.ngOptions.match(NG_OPTIONS_REGEXP))) {
var values = $parse(match[7]);
scope.$watchCollection(values, function () {
// Redraw this select element
$timeout(function () {
var originalWidth = $(elem).css('width');
$(elem).css('width', '0');
$(elem).css('width', originalWidth);
}, 10);
});
}
}
};
}]);