場景: 我創建了一個文件的服務,讓所有文件上的負載從Angularjs:AJAX結果沒有在控制器中加載
myModule.factory('DocumentService', ['$http', '$resource', function ($http,$resource) {
var docArray = [];
$http.get('/Scripts/json/documents.json').then(function (response) {
docArray = response.data;
});
_getDocuments = function() {
return docArray;
}
return {
getDocuments: _getDocuments
}
}]);
我創建了一個文件控制器,從文件獲取值JSON文件服務
myModule.controller('HomeController', ['$scope', 'DocumentService','$http', function ($scope, docservice, $http) {
$scope.documents = docservice.getDocuments();
}]);
和HTML
<div class="btn btn-primary col-xs-12 padding-rm-bs" data-toggle="button" ng-repeat="document in documents" ng-click="changePrimaryRightPanel(document)">
<div class="col-xs-10 ">
<ul class="list-inline pull-left">
<li>
<span ng-show="document.hide==true" >{{document.id}}</span>
<img ng-src="{{document.status |DocStatusFilter}}" width="12" height="16"></li>
<li>{{document.name}}</li>
</ul>
<ul class="list-inline pull-right">
<li></li>
</ul>
</div>
<div class="col-xs-2 ">
<ul class="list-inline pull-right text-right">
<li>{{document.size | DocSizeFilter}} </li>
<li><span title="{{document.lastModified}}">{{document.lastModified}} </span> </li>
</ul>
</div>
</div>
Documents.json
[
{
"id": 1,
"status": 1,
"name": "Draft Contract",
"size": 2306867.2,
"lastModified": "1-1-2013"
}
]
問題: $ scope.documents犯規得到填充結果。
,但如果我做的控制器的變化和控制器移動服務功能,那麼它工作正常
$http.get('/Scripts/json/documents.json').
then(function (response) {
$scope.documents = response.data;
});
我怎樣才能解決這個問題。基本上我想我的文檔服務來獲取,更新,刪除,添加文檔,並希望我的控制器只是調用文檔服務的方法
是這種做事的方式,或者我需要污染我的控制器的承諾?
可以有人指導我這是處理工廠和控制器和他們的溝通 任何幫助將不勝感激
一切正常,因爲它應該工作。 – TheHippo
@TheHippo wat你的意思是一切正常? – Salman
你的服務交給'then'的函數會在控制器初始化後被調用很長時間。 – TheHippo