永远不会执行AngularJS http请求

时间:2013-07-10 12:23:30

标签: javascript angularjs angularjs-directive angularjs-scope

我对此here有一个最小的插入。

以下是发生的事情:

  1. 初始$http请求已成功完成
  2. 点击事件绑定到指令
  3. 中的按钮
  4. 点击按钮可触发所需功能
  5. 该函数中的$http请求(与步骤1中的请求相同)不会触发
  6. 因为代码很短,我也会在这里发布。

    模板

    <!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"
    }
    

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

1 个答案:

答案 0 :(得分:3)

您必须通过在范围上调用$ apply()来传播承诺解析。

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

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