1

我在这里有一点点小插曲。

这是正在发生的事情:

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

知道为什么该请求不执行吗?

4

1 回答 1

3

您必须通过在作用域上调用 $apply() 来传播承诺解决方案。

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

  link: (scope, element, attrs) ->
    element.bind 'click', (e) -> scope.act(); scope.$apply();
于 2013-07-10T12:52:07.760 回答