Andy Andy - 2 months ago 22
Javascript Question

JavaScript code works perfectly in other browsers but breaks AngularJS in ie11?

I'm using this nice directive that replicates jQuery's slideToggle in AngularJS, I've found it does not work in IE11. No errors, the code just doesn't work when you open the fiddle in IE11. Any ideas of how to 'fix' it so that it works in IE11?

http://jsfiddle.net/rh7z7w0a/2/

angular.module('angularSlideables', [])
.directive('slider', function () {
return {
restrict:'A',
compile: function (element) {
// wrap tag
var contents = element.html();
element.html('<div class="slideable_content" style=" margin:0 !important; padding:0 !important" >' + contents + '</div>');

return function postLink(scope, element, attrs) {
var i = 0;
// default properties
scope.$watch(attrs.slider, (n, o) => {
if (n !== o) {
i++;
var target = element[0],
content = target.querySelector('.slideable_content');
if(n) {
content.style.border = '1px solid rgba(0,0,0,0)';
var y = content.clientHeight, z = i;
content.style.border = 0;
target.style.height = y + 'px';
setTimeout(() => {
if (z === i) {
target.style.height = 'auto';
}
}, 500);
} else {
target.style.height = target.clientHeight + 'px';
setTimeout(() => {
target.style.height = '0px';
});
}
}
});

attrs.duration = (!attrs.duration) ? '0.5s' : attrs.duration;
attrs.easing = (!attrs.easing) ? 'ease-in-out' : attrs.easing;
element.css({
'overflow': 'hidden',
'height': '0px',
'transitionProperty': 'height',
'transitionDuration': attrs.duration,
'transitionTimingFunction': attrs.easing
});
};
}
};
});


The problem seems to be to do with this section:

scope.$watch(attrs.slider, (n, o) => {

Answer

Arrow functions are not supported in IE11, so (n, o) => is considered invalid syntax by IE11. You should be able to use a normal anonymous function instead, like this:

scope.$watch(attrs.slider, function(n, o) {
    ...
});

Bear in mind that this behaves differently in anonymous functions than it does to arrow functions. In your case, that isn't a problem, but it's worth reading the MDN documentation on arrow functions to know the differences.

You might also want to consider a transpiler such as Babel if you want to use all of the latest ES6 features without breaking compatibility for older browsers. Babel can convert newer code into the equivalent ES5 which is supported by nearly all browsers created within the last few years.