问题描述:

I have a minimal plunk of this here.

Here's what's happening:

  1. initial $http request is made successfully
  2. a click event is bound to a button in a directive
  3. clicking the button fires the desired function
  4. the $http request in that function (identical to the request in step 1) does not fire

Because the code is short, I'll post it here, too.

template

<!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()

data

{

"name": "gaius baltar"

}

Any idea why that request doesn't execute?

网友答案:

You have to propagate promise resolution, by calling $apply() on the scope.

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

  link: (scope, element, attrs) ->
    element.bind 'click', (e) -> scope.act(); scope.$apply();
相关阅读:
Top