这是交易。我有一个页面,您只需编辑用户。它有基本的输入和一切。然后我创建了一个指令来处理通过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 for file in this.files
req = new XMLHttpRequest()
req.open 'POST', attrs.postUrl, true
req.onreadystatechange = =>
if req.readyState is 4
if req.status is 200
response = JSON.parse req.responseText
notarray = attrs.notArray is "true"
if notarray
response = response[0]
scope.fileUpload = response
scope.$apply()
req.send form
该指令的使用方式如下:
<input type="file" file-upload="member.image" post-url='/members/images' not-array="true"/>
一切都运行正常,但我希望用户的图像在其自己的组件中,所以我创建了一个如此指令:
<member-img member='member' ></member-img>
使用会员的姓名和图片来显示数字。如果它有帮助,这是指令:
).directive('memberImg', ()->
scope:
member: "="
restrict: "E"
templateUrl: 'partials/member-image.html'
link: (scope, element, attrs)->
failed = false
setImage = ->
scope.image = if scope.member.image and scope.member.image isnt '' and 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()
)
无论如何,出于某种原因,将其放入自己的目录中,图像只会在50%的时间内上传。更奇怪的是,在我的fileUpload指令中,如果我两次调用$ apply,它每次都有效:
.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 for file in this.files
req = new XMLHttpRequest()
req.open 'POST', attrs.postUrl, true
req.onreadystatechange = =>
if req.readyState is 4
if req.status is 200
response = JSON.parse req.responseText
notarray = attrs.notArray is "true"
if notarray
response = response[0]
scope.fileUpload = response
scope.$apply()
scope.$apply() # For some reason I have to call this twice.
req.send form
else
throw "fileUpload requires post-url attribute!"
我认为可能发生的事情是,在第一次应用时,它通知父范围member.image应该更改,然后在第二个应用父范围通知另一个子成员应该更改。但是,我知道这不是预期的行为。任何关于这个问题的光都会受到赞赏。