Scenario: i have created a document service that get all documents on load from json file
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
}
}]);
i have created a Document controller that get values from document service
myModule.controller('HomeController', ['$scope', 'DocumentService','$http', function ($scope, docservice, $http) {
$scope.documents = docservice.getDocuments();
}]);
and in 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"
}
]
Issue: $scope.documents doesnt get populated with result.
but if i make changes in controller and move service functionality in controller then it works fine
$http.get('/Scripts/json/documents.json').
then(function (response) {
$scope.documents = response.data;
});
how can i solve this issue. basically i wanted my document service to get , update , delete , add documents and want my controller just to call methods of document service
is this rite way of doing thing or i need to pollute my controllers with promises?
can some one guide me which is the best practice to handle factory and controller and their communication any help will be appreciated