我对此here有一个最小的插入。
以下是发生的事情:
$http
请求已成功完成$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"
}
知道为什么不执行该请求?
答案 0 :(得分:3)
您必须通过在范围上调用$ apply()来传播承诺解析。
app.directive 'makeRequest', ($compile) ->
scope:
act: '&'
link: (scope, element, attrs) ->
element.bind 'click', (e) -> scope.act(); scope.$apply();