javascript - $scope.$apply() in angular working but throwing error -
i put isolated example in jsbin: http://jsbin.com/deqerelita/1/
scenario idea simple. click button, controller adds model, view gets updated accordingly hidden input type="file". after view updated, controller clicks last file input added.
problem when controller clicks file input before running $scope.$apply() nothing happens till second click, presumably because angular has not registered new input yet. when run $scope.$apply() console throws errors click input.
here html:
<div ng-controller="filebuttons"> <input type="button" ng-click="handleimage.add()" value="add file button"/> <div class="imageuploadpreviewcontainer"> <div class="imageuploadpreview hide" data-ng-repeat="file in files" file-index="{{$index}}"> <input type="file" class="hide"/> </div> </div> </div> </div></div> here angular js:
var myapp = angular.module('myapp', []); myapp.controller('filebuttons', ['$scope', '$log', function($scope, $log){ $scope.files = []; $scope.handleimage = { add: function(){ $scope.files.push({ state : 'started' }); $log.log('added'); $scope.$apply(); angular.element('.imageuploadpreviewcontainer .imageuploadpreview:last input[type=file]').trigger('click') } } } ]); completely new angular pardon noooobish design flaws
i use $timeout
var myapp = angular.module('myapp', []); myapp.controller('filebuttons', ['$scope', '$log','$timeout', function($scope, $log, $timeout) { $scope.files = []; $scope.handleimage = { add: function() { $scope.files.push({state : 'started'}); $log.log('added'); $timeout(function() { angular.element('.imageuploadpreviewcontainer .imageuploadpreview:last input[type=file]').trigger('click') },0); } }; } ]);
Comments
Post a Comment