I am fetching data from a JSON file and saving it in an object array. Then I want to share the array between two controllers one controller is showing the data in the page while other can add objects to the array using a modal. But the problem is I am unable to render the data into the page. The object array is empty.
Here is the service.
.service('Faq', function ($http) {
this.faqList = [];
$http.get('/Json/faq.json').then(function (result) {
// process your results here
this.faqList = result.data;
});
this.getFaqs = function (){
return this.faqList;
}
this.addfaq = function (obj) {
this.faqList.push(obj);
};
})
Controller to render the data
.controller('AppCtrl', function ($scope, $modal, Faq) {
$scope.filteredFaqData = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.faqData = [];
$scope.faqData = Faq.getFaqs();
$scope.$watch('currentPage + numPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredFaqData = $scope.faqData.slice(begin, end);
});
$scope.show = function () {
$modal.open({
templateUrl: "faqAddUpdate.html",
controller: "faqctrl"
});
};
$scope.deleteFaq = function (id) {
var l = $scope.faqData.length;
for (var i = 0; i < l; i++) {
if ($scope.faqData[i].id == id) {
$scope.faqData.splice(i, 1);
break;
}
}
console.log(id);
};
})
Controller for the modal
.controller('faqctrl', function ($scope, $modalInstance, Faq) {
$scope.question = '';
$scope.id = '';
$scope.answer = '';
$scope.editFaq = function (id) {
$scope.divFaq = true;
$scope.faqs = [];
Faq.getData().then(function (msg) {
$scope.faqs = msg.data;
var l = $scope.faqs.length;
for (var i = 0; i < l; i++) {
if ($scope.faqs[i].id == id) {
$scope.question = $scope.faqs[i].question;
$scope.id = $scope.faqs[i].id;
$scope.answer = $scope.faqs[i].answer;
$scope.Action = "Update";
}
}
});
};
$scope.AddUpdateFAQ = function () {
var faq = {
id: $scope.id,
question: $scope.question,
answer: $scope.answer
};
Faq.addfaq(faq);
console.log(faq);
$modalInstance.close();
};
$scope.Cancel = function () {
$modalInstance.dismiss();
};
});
The problem is in the service because initially when I was getting the array like this
this.faqList = $http.get('/Json/faq.json');
Data was populating but when-when I was updating it was throwing error this.faqlist.push is not a function then someone on the StackOverflow told me told me that the above line changing the array to promise so I made the changes but it is not populating the data now.