我正在使用 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.
});
};
}];
它只是对简单 JSON 文件的调用。
我的 HTML 如下:
<div class="container main-frame" ng-app="projectsApp" ng-controller="filtersController" ng-init="init()">
</div>
由于某种原因,每次我加载页面时,这个 get 调用都会被调用两次。这是标准行为吗?
非常感谢,
Dash
此问题也可能是由于具有ng-app
路由到您的控制器和ng-controller
在您的页面中引用。例如,如果您的应用程序如下所示:
<html lang="en" ng-app="myApp">
<head>...</head>
<body>
<div ng-controller="myController">
...
</div>
</body>
</html>
Javascript 定义应用程序:
angular.module('myApp',[]) {
$routeProvider.when('/path', {templateUrl: '...', controller: myController);
在上面的情况下,通过定义到 myController 的路由,控制器将被实例化两次,您将看到如上所述的两个调用。
Updated
上面的代码描述了问题所在,但缺少正确的解决方案,因此我根据@Intrepid 评论更新了答案。
需要删除ng-controller="myController"
如果您已经在路线中定义了,请从您的 html 模板中获取。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)