簡體   English   中英

永遠不會執行AngularJS http請求

[英]AngularJS http request is never executed

在這里有一個最小的插件。

這是發生了什么:

  1. 初始$http請求成功完成
  2. click事件綁定到指令中的按鈕
  3. 單擊該按鈕可觸發所需的功能
  4. 該函數中的$http請求(與步驟1中的請求相同)不會觸發

因為代碼很短,我也會在這里發布。

模板

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <title>AngularJS Plunker</title>
    <!-- angular source -->
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Click this button and an http request should log to the console</p>
    <button make-request act='flip()'>Get Gaius</button>
  </body>

</html>

調節器

app = angular.module('plunker', [])

app.controller 'MainCtrl', ($scope, $http) ->
  # this function is just here to show that no errors are thrown
  err = (err) -> console.log 'err', err

  # this successfully gets
  $http.get('gaius.json')
    .then ((res) -> console.log 'init data', res.data), err


  $scope.flip = ->
    # although this function is called,
    console.log 'called to act'
    # http does not get. No request is made.
    $http.get('gaius.json')
      .then ((res) -> console.log 'flip data', res.data), err

app.directive 'makeRequest', ($compile) ->
  scope:
    act: '&'

  link: (scope, element, attrs) ->
    element.bind 'click', (e) -> scope.act()

數據

{
  "name": "gaius baltar"
}

知道為什么這個請求不執行?

您必須通過在作用域上調用$ apply()來傳播promise promise。

app.directive 'makeRequest', ($compile) ->
  scope:
    act: '&'

  link: (scope, element, attrs) ->
    element.bind 'click', (e) -> scope.act(); scope.$apply();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM