【问题标题】:AngularJS update scope value in PromiseAngularJS 更新 Promise 中的范围值
【发布时间】:2017-11-10 06:50:16
【问题描述】:

所以我有这个代码

  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

它与视图无关,问题值只是不想在控制器中更新

【问题讨论】:

    标签: angularjs coffeescript


    【解决方案1】:

    这行代码会立即触发:

       console.log(@$.question) 
    

    因为它是一个 IIFE(立即调用函数表达式)。

    您需要在回调中才能从 Promise 中写出数据:

     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
    

    如果您需要附加到该值,您可能需要使用 Observable

    您还可以在顶部声明您的变量以使其可供整个类访问:

    init: ->
        @loadRootQuestion()
        @answerValue // assign to this value
    
      methods:
    
        loadRootQuestion: () ->
          @$http.get(api_replies_path()).then(
            (response) =>
              @$.question = response.data.replies[0]
              @loadAnswers()
          )
    

    【讨论】:

    • console.log 只是为了解释我的问题,它没有在视图中更新。我所需要的只是覆盖该变量,但在 http 调用之外它没有任何效果
    • 抱歉,您需要在哪里更新@$.question?在视图中?你能告诉我那个代码吗?
    【解决方案2】:

    在promise 内部@$.question 有它自己的范围,它在promise 之外是不可用的。

    您可以在 http 调用之外声明一个变量,并更新 promise 中的值并将其分配给 @$.question。

    【讨论】:

    • 感谢您的回答,但不幸的是,这不起作用。似乎 http 有自己的范围,它是最后执行的,这就是我猜它无法更新值的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2013-05-31
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多