所以我有这个代码
init: ->
@loadRootQuestion()
methods:
loadRootQuestion: () ->
@$http.get(api_replies_path()).then(
(response) =>
@$.question = response.data.replies[0]
@loadAnswers()
)
loadAnswers: () ->
@$http.get(api_replies_path(), params: {parent_id: @$.question.id}).then(
(response) =>
@$.answers = response.data.replies
)
next: (answerId) ->
@$http.get(api_replies_path(), params: {parent_id: answerId}).then(
(response) ->
@$.question = response.data.replies[0] // I get value I need here
)
console.log(@$.question) // can't get it here
问题是范围变量在下一个方法中无法在此承诺之外更新,我做错了什么?
更新
.modal-header
button.close type='button' ng-click='close()' data-dismiss="modal" aria-label="Close"
span
| ×
h3.modal-title
| {{ question.content }}
.modal-body
select name="answerSelect" ng-model="answer"
option ng-repeat='answer in answers' value="{{ answer.id }}"
| {{ answer.content }}
.modal-footer
button.btn.btn-primary.pull-left ng-if="showPreviousButton" ng-click="previous(question)" Prev
button.btn.btn-primary.pull-right ng-if="showNextButton" ng-click="next(answer)" Next
它与视图无关,问题值只是不想在控制器中更新
答案 0 :(得分:0)
这行代码将立即触发:
p
因为它是IIFE(立即调用的函数表达式)。
您需要在回调中才能写出承诺中的数据:
console.log(@$.question)
如果您需要附加到该值,则可能需要使用 Observable 。
您还可以将变量顶部声明,以使整个类都可以访问:
next: (answerId) ->
@$http.get(api_replies_path(), params: {parent_id: answerId}).then(
(response) ->
@$.question = response.data.replies[0] // I get value I need here
console.log(@$.question) // you CAN get it here!
)
console.log(@$.question) // can't get it here
答案 1 :(得分:-1)
在承诺@ $。问题内部有自己的范围,并且在承诺之外不可用。
你可以在http调用之外声明一个变量并更新promise中的值并将其分配给@ $。question。