Reputation: 1206
I am trying to work on SPA and have declared a factory like this
// configure the PersonalDetails service
app.factory("PDService", function ($http) {
var thisPDService = {};
// get the data from database
thisPDService.Get = function () {
var promise = $http({
method: 'GET',
url: '/api/PersonalDetails'
})
.then(function (response) {
return response.data;
},
function (response) {
return response.data;
});
return promise;
};
return thisPDService;
});
My controller looks like this
app.controller("PDController", function ($scope, PDService) {
$scope.Title = "Personal Details List";
$scope.GetMyData = PDService.Get().then(function (d) {
$scope.PersonalDetails = d;
});
});
and view is
<table class="table table-striped table-responsive">
<tr>
<th>First Name</th><th>Last Name</th><th>Age</th><th>Active</th>
</tr>
<tr ng-repeat="d in PersonalDetails">
<td>{{d.FirstName}}</td><td>{{d.LastName}}</td><td>{{d.Age}}</td><td>{{d.Active}}</td>
</tr>
</table>
All works great but the problem is when I navigate to this view, it automatically calls the Get() method of the PDService that loads the data in the table. I do not want to do that.
Even if I declare another method in the factory, that method also gets called automatically.
Any help will much appreciated.
Upvotes: 0
Views: 57
Reputation: 3987
You are calling the .Get() method of the service in your controller.
$scope.GetMyData = PDService.Get().then(function (d) {
$scope.PersonalDetails = d;
});
This line assigns the result of your .Get() method to the variable $scope.GetMyData.
Instead, try:
$scope.GetMyData = PDService.Get;
Or, better yet, just inject the $http service into your controller and create a get function there. Your service is just a wrapper around $http with a specific URL, which could be stored as a constant instead.
$scope.getMyData = function() {
$http.get('/api/PersonalDetails')
.then(handleSuccess, handleError);
};
Upvotes: 0
Reputation: 937
you should change the controller like this.
$scope.GetMyData = function() {
PDService.Get().then(function (d) {
$scope.PersonalDetails = d;
});
};
and when you need to fill the data, just call GetMyData
Upvotes: 1