これは少し複雑です。私の質問を説明するために最善を尽くします。
まず、すべての ajax が要素をトリガーして、リクエストが処理中であることを示すようHttpService
にラップする を作成します。以下のサービスです。$http
#loading
angular.module('HttpServices', [])
.factory('HttpWrapper', ['$http', '$rootScope', function($http, $rootScope) {
$http.defaults.transformRequest.push(function(data) {
$rootScope.loading = ($rootScope.loading ? $rootScope.loading + 1 : 1);
console.log('start request') # this will be triggered by template load!!
console.log(data); # the template will be printed to the console!!
return data;
});
$http.defaults.transformResponse.push(function(data) {
$rootScope.loading -= 1;
console.log('finish request');
console.log(data);
return data;
});
return $http;
}]);
次に、非常に単純なルートがあります。
@myapp = angular.module('myapp', ['HttpServices'])
myapp.factory('Service', ['HttpWrapper', ($http) ->
service = {}
service.data = [1..3]
service
])
myapp.config (['$routeProvider', ($routeProvider) ->
$routeProvider
.when('/', {
templateUrl: 'home.html',
resolve: {
data: ['Service', (Service) ->
Service.data
]
}
})
.when('/test', {
templateUrl: 'test.html'
})
])
次に、htmlも非常に単純です。
<div data-ng-app='myapp'>
<ul>
<li><a href="#/">home</a></li>
<li><a href="#/test">test</a></li>
</ul>
<div id="loading" ng-show="loading">loading</div>
<div ng-view></div>
<script type="text/ng-template" id="home.html">
home
</script>
<script type="text/ng-template" id="test.html">
test
</script>
</div>
ほら、テンプレートは単なるインラインテンプレートです。それらはng-view
要素のすぐ後ろにあります。しかし、リンク #/またはリンク #/testをクリックすると、Ajax リクエストが送信されたのと同じように、http ラッパーがトリガーされます。なんで?それらは単なるインライン テンプレートです。なぜトリガーするの$http
ですか?実際にはバックエンドとの通信はありません。