javascript - AngularJS http 请求永远不会执行

标签 javascript angularjs angularjs-directive angularjs-scope

我对这个 here 有一点了解.

这是发生了什么:

  1. 初始$http请求成功
  2. 点击事件绑定(bind)到指令中的按钮
  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>

Controller

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 解决方案。

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

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

关于javascript - AngularJS http 请求永远不会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17570582/

相关文章:

mysql - 在 AngularJS 指令上显示和存储不同的日期格式

angularjs - 如何在 AngularJS 中生成即时指令?

angularjs - 在嵌套指令中传递 ng-model

javascript - SignalR C# 客户端未调用方法

javascript - AngularJS + ADAL.JS 设置资源 ID(受众)

angularjs - 使用 ng-options 选择且模型中未设置默认值的 IE10 始终选择下拉列表中的第一个元素

javascript - 使用 AngularJS 绑定(bind)后如何获取元素的字符串长度?

javascript - 当我在下面的代码中输入 jquery 时如何过滤我的复选框?

javascript - 在不使用 Canvas 的情况下在 JavaScript 中调整 Base-64 图像的大小

javascript - 带有混合图表的 Chart.js OnClick 事件,我点击了哪个图表?