我从角度调用REST服务,它总是调用工厂两次.这是工厂代码.
app.factory('dataFactory',['$http',function ($http) { var urlBase = '/api'; var dataFactory = {}; dataFactory.getMyItems = function () { return $http.get(urlBase + '/MyItems'); }; return dataFactory; } ]);
app.controller('MyItemsController',['$scope','dataFactory',function ($scope,dataFactory) { $scope.myItems; getItems(); function getItems() { dataFactory.getMyItems() .success(function (itemsData) { $scope.myItems = itemsData; }) .error(function (error) { $scope.status = 'Unable to load items data: ' + error.message; }); } } ]);
我有同样的问题,你的控制器一般叫两次;因此,工厂将被召唤两次.
但是在看了这个解决方案之后:
Combating AngularJS executing controller twice@H_403_4@
步骤1:@H_403_4@
确保您只在(主布局视图)中添加服务和控制器一次.@H_403_4@
例:@H_403_4@
的index.html@H_403_4@
<script src="../MyItemsController.js"></script> <script src="../MyItemsService.js"></script>
如果在执行步骤1后仍然存在问题,请转到步骤2@H_403_4@
第2步:@H_403_4@
1.将控制器保留在您的视图(ng-controller)中,并将其从配置路由中删除,如下所示:@H_403_4@
路由配置(通常是app.js):@H_403_4@
app.config(['$routeProvider',function($routeProvider){ $routeProvider.when('/',{ templateUrl: 'pages/home.html' //Remove controller from here }); }]);
home.html的@H_403_4@
<!-- Add the ng-controller in your view --> <div ng-controller="MyItemsController"> <!-- Your stuff --> </div>
2.或者将控制器保留在您的配置路由中,并删除控制器
从这样看:@H_403_4@
路由配置(通常是app.js):@H_403_4@
app.config(['$routeProvider',{ templateUrl: 'pages/home.html',controller: 'MyItemsController' //Add the controller here }); }]);
home.html的@H_403_4@
<!-- Remove the ng-controller in your view --> <div> <!-- Your stuff --> </div>