iam*_*ash 10 json http angularjs
我正在使用Angular开发一个页面,并在我的控制器中有一个init()方法.代码如下:
var filtersController = ['$scope', '$http', function ($scope, $http) {
$scope.init = function () {
$http({
method: 'GET',
url: '/json-tags-test',
cache: true
}).success(function (data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
}];
Run Code Online (Sandbox Code Playgroud)
它只是对一个简单的JSON文件的调用.
我的HTML如下:
<div class="container main-frame" ng-app="projectsApp" ng-controller="filtersController" ng-init="init()">
</div>
Run Code Online (Sandbox Code Playgroud)
出于某种原因,每次加载页面时,此get调用都会调用两次.这是标准行为吗?
非常感谢,
短跑

小智 53
此问题也可能是由于ng-app您的控制器路由与ng-controller页面中的引用有关.例如,如果您的应用看起来像:
<html lang="en" ng-app="myApp">
<head>...</head>
<body>
<div ng-controller="myController">
...
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
定义应用程序的Javascript:
angular.module('myApp',[]) {
$routeProvider.when('/path', {templateUrl: '...', controller: myController);
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,通过定义到myController的路由,控制器将被实例化两次,你将看到两个调用,如上所述.
更新
上面的代码描述了什么是问题,但缺少什么是正确的解决方案,所以我根据@Intrepid评论更新了答案.
ng-controller="myController"如果您已在路线中定义,则需要从html模板中删除.
我不认为这是越来越叫了两声,我就创建了一个普拉克给你看这个.
var app = angular.module('projectsApp', []);
app.controller('filtersController', ['$scope', '$http', function ($scope, $http) {
$scope.status = 'Page loading';
var count = 0;
$scope.init = function () {
$scope.status = 'API called';
$http({
method: 'GET',
url: '/json-tags-test',
cache: true
}).success(function (data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('success');
count++;
$scope.status = 'successful: '+ count;
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('error');
count++;
$scope.status = 'failed times: '+ count;
});
};
}]);
Run Code Online (Sandbox Code Playgroud)
来自DEV工具的XHR日志

编辑:
使用虚拟json文件更新了plunk
http://plnkr.co/edit/hTdtLK?p=preview

正如你再次看到它只被调用一次.清除日志我猜你正在看到上一页加载的日志,在预览模式下,coz更改立即可见.
| 归档时间: |
|
| 查看次数: |
21089 次 |
| 最近记录: |