0

I've fixed a problem but I don't understand something that I would like to.

In this SO question I asked why the dom isn't being updated on change and was suggested to me that I use scope.$apply() to do so: Angular not updating Ng-class when on-change is triggered

My question is why when I put scope.$apply() at the end of my function makes my code work but when I put it in the reader.onload function or after the scope.slideMenuToggle() function it does not work?

    /**
     * Triggers reader for when an image has been selected from the input
     * @param element - Saves the input value to this scope.
     */

    scope.setImageFile = function (element) {
        var reader = new FileReader();

        // Converts the image to a data URL.
        reader.readAsDataURL(element.files[0]);
        scope.slideMenuToggle();

        /**
         * When chosen image is selected it triggers the onload function to pass the image to the whiteboardService.
         * @param event - Saves the event of the input field to get the images data URL.
         */
        reader.onload = function (event) {
            fabric.Image.fromURL(event.target.result, function (img) {
                whiteboardService.uploadImageToCanvas(img);
            });

            // Resets the form that wraps round the file input to allow the
            // user to add more than one of the same file.
            // NOTE: This will break other inputs if you put them inside this form
            $('.app-set-image-file-form').trigger('reset');
        };

        scope.$apply();
    };

Ta

Community
  • 1
  • 1
Max Lynn
  • 1,738
  • 6
  • 22
  • 35
  • what is wrong in this example when you are moving apply()? – alexey Mar 11 '16 at 13:37
  • Hi Alex, Thanks for commenting, Basically if I put the scope.apply() in any other place than where it is in my example it fails to reload the scope in the DOM when scope.slideMenuToggle() changes a variable that is set to false once this function runs. – Max Lynn Mar 11 '16 at 14:32

0 Answers0