我对这个 here 有一点了解.
这是发生了什么:
- 初始
$http
请求成功 - 点击事件绑定(bind)到指令中的按钮
- 点击按钮触发所需的功能
- 该函数中的
$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/