I am trying to read names from the JSON file. I first created without services using the only controller.But then to moved the business logic to services. I am not getting a clear idea that about how to return the $scope.mydata from service to the controller.
Not getting any output please help. Thank you.
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Add angularjs -->
<!-- Add controller script-->
<script type="text/javascript">
var app = angular.module('x2js', []);
app.controller('ctrl',
['$scope','myService',function($scope,myService){
$scope.data = function(){
myService.getData()
}
}]);
app.service('myService', ['$http','$log', function($http,$log){
this.getData = function(){
$http({
url:"student.json",
method:"GET",
dataType: 'json',
contentType: "application/json"
}).then(function(response){
$scope.myData = response.data.records;
$log.info($scope.post);
return($scope.myData);
},function(response){
$log.error("Error occured");
});
}
}])
</script>
</head>
<body ng-app="x2js">
<div ng-controller="ctrl">
<table>
<tr>
<td ng-repeat="x in Data">{{x.Name}}</td>
</tr>
</table>
</div>
</body>
</html>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…