简体   繁体   中英

Triggering a click event from within an angularjs function causes an error

I'm getting the error

[$rootScope:inprog] $apply already in progress

whenever I trigger a click event on a hidden file upload input.

HTML:

<!-- button that calls function in controller -->
<button type="button" ng-click="uploadClicked()">Upload</button>
<!-- Upload input I'm triggering the click event on -->
<input type="file" accept="image/*" id="profile-photo" name="profile-photo" ng-hide="true"/>

AngularJS function in controller:

$scope.uploadClicked = function () {
    //Causes Error: [$rootScope:inprog] $apply already in progress and opens file dialog
    document.getElementById('profile-photo').click();

    //Causes Error: [$rootScope:inprog] $apply already in progress and does not open file dialog
    $('#profile-photo').trigger('click');
};

I'm not calling $apply or $digest anywhere in my controller. Why would this error be occurring?

I just got a similar issue and i was able to fix that by wrapping the place where we click with a

 setTimeout(function(){uploadClicked();},0);

the angular version would be

$timeout(function(){uploadClicked();},0);

By using angular version, Angular will be aware and will not initialize another digest cycle on finding a click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM