javascript - Angular Directives: I have to call $apply twice? -
here's deal. have page edit user. has basic inputs , everything. created directive handle uploading of images through ajax:
angular.module('filedirectives', []) .directive('fileupload', ($http, $parse)-> scope: fileupload: "=" link: (scope, element, attrs)-> if attrs.posturl element.bind 'change', -> if this.files.length > 0 form = new formdata() form.append 'files[]', file file in this.files req = new xmlhttprequest() req.open 'post', attrs.posturl, true req.onreadystatechange = => if req.readystate 4 if req.status 200 response = json.parse req.responsetext notarray = attrs.notarray "true" if notarray response = response[0] scope.fileupload = response scope.$apply() req.send form
the directive used this:
<input type="file" file-upload="member.image" post-url='/members/images' not-array="true"/>
everything working fine, wanted user's image in it's own component, created directive so:
<member-img member='member' ></member-img>
which uses member's name , image display figure. if it'll help, here's directive:
).directive('memberimg', ()-> scope: member: "=" restrict: "e" templateurl: 'partials/member-image.html' link: (scope, element, attrs)-> failed = false setimage = -> scope.image = if scope.member.image , scope.member.image isnt '' , not failed scope.member.image else "default.gif" setimage() scope.$watch 'member.image', -> failed = false setimage() element.find('img').bind 'error', ()-> scope.$apply -> failed = true setimage() )
anyways, reason putting it's own directory, image gets uploaded 50% of time. what's weirder in fileupload directive, if call $apply twice, works everytime:
.directive('fileupload', ($http, $parse)-> scope: fileupload: "=" link: (scope, element, attrs)-> if attrs.posturl element.bind 'change', -> if this.files.length > 0 form = new formdata() form.append 'files[]', file file in this.files req = new xmlhttprequest() req.open 'post', attrs.posturl, true req.onreadystatechange = => if req.readystate 4 if req.status 200 response = json.parse req.responsetext notarray = attrs.notarray "true" if notarray response = response[0] scope.fileupload = response scope.$apply() scope.$apply() # reason have call twice. req.send form else throw "fileupload requires post-url attribute!"
i think may happening on first apply, it's notifying parent scope member.image should change, on second apply parent scope's notifying other child member should change. however, know not intended behavior. light shed on subject appreciated.
Comments
Post a Comment