Search code examples
angularjsecmascript-6ecmascript-5

Conversion from ES6 to ES5 throwing Syntax error


I am trying to convert a directive from ES6 to ES5. It is giving me syntactical errors at scope stating "Expecting newline or semicolon" and also at link : function stating "Function statement should be at top level of program". Can someone help change this ES6 directive to ES5

Directive in ES6

directives.directive('clickAndWait', () => ({
        restrict: 'A',
        scope: {
            asyncAction: '&clickAndWait',
        },
        link: (scope, element) => {
        element.bind('click', () => {

        element.prop('disabled', true);
    // element.addClass('state-waiting');
    scope.$apply(() => {
        scope.asyncAction().finally(() => {
        element.prop('disabled', false);
    // element.removeClass('state-waiting');
});
});
});
},
}));

My code in ES5

        directives.directive('clickAndWait', function () {
       return {
           restrict : 'A',
           scope : {
               asyncAction: '&clickAndWait'
           },
           link : function(scope, element, attr) {
               element.bind('click', function(){
                   element.prop('disabled', true);
                   scope.$apply(function () {
                       scope.asyncAction().finally(function () {
                           element.prop('disabled', false);
                       })
                   })
               });
           }
       }

    });

Solution

  • Mostly renaming () => { to function () {. But also making sure to add the return statement to the directive function, which is implicit in arrow functions.

    directives.directive('clickAndWait', function() {
        var directiveConfig = {
    
            restrict: 'A',
            scope: {
                asyncAction: '&clickAndWait',
            },
            link: function(scope, element) {
                element.bind('click', function() {
    
                    element.prop('disabled', true);
                    scope.$apply(function() {
                        scope.asyncAction().finally(function() {
                            element.prop('disabled', false);
                        });
                    });
                });
            }
        };
    
        return directiveConfig;
    });