我正在尝试从JSON文件中读取名称。我首先使用唯一的控制器创建没有服务的服务,然后将业务逻辑转移到服务。我没有清楚地知道如何将$ scope.mydata从服务返回给控制器。 没有得到任何输出,请帮助。谢谢。在AngularJS中使用服务将对象值返回给控制器
<!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>
仍然没有输出。 :( –
@AmitPhartiyal你使用'Data'到html和控制器的值分配给'data'变量 –
其实它是myData在他的例子中 – pegla