ngImgCrop not working inside UI Modal

让人想犯罪 __ 提交于 2019-12-24 00:11:52

问题


I am using the ngImgCrop angular directive to resize and crop an image. However when I try and use it inside a UI Modal controller it doesn't work.

The issue I believe is that the below line does not get properly set because the DOM is not created. The handlefileselect function never gets called?!

Does anybody know how to properly use this directive inside a Modal or how to make this work?

angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);

The modal contoller code is here

.controller('ProfilePictureModalInstanceCtrl', function ($scope, $modalInstance, items,$timeout) {

    $scope.myImage = '';
    $scope.myCroppedImage = '';

    var handleFileSelect = function (evt) {

        alert("Here");

        var file = evt.currentTarget.files[0];
        var reader = new FileReader();
        reader.onload = function (evt) {
            $scope.$apply(function ($scope) {
                $scope.myImage = evt.target.result;
            });
        }
        reader.readAsDataURL(file);
    }


    angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);

    $scope.ok = function () {
        $modalInstance.close($scope.optionItems);
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});

回答1:


Your suspicion is spot on. I had a similar issue and the problem is with that line:

angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);

The problem here is you are trying to bind an event on a DOM element that might not exist at the time you do the binding. I found a work around that others were using (more info here). The work around is to wrap the binding in a timeout like below:

$timeout(function() {
    angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
},1000, false);

The above will try to do the binding a second later after the modal controller code executes. You can increase the delay if necessary.



来源:https://stackoverflow.com/questions/30540382/ngimgcrop-not-working-inside-ui-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!