【发布时间】:2016-06-01 17:40:33
【问题描述】:
我已经创建了用于从服务器获取数据的单独服务,但我想将此服务返回的数据分配给控制器中的变量。在这种情况下,数据是一个简单的 JSON 文件。
这是我的服务
angular.module('app')
.service('TextService', ['$http', function CompanyService($http) {
var service = {};
$http.get('text.json').
then(function (response) {
service.text = response.data.text;
console.log(response.data.text);
}, function (response) {
alert(response);
});
return service;
}]);
这是我的控制器
app.controller("myCtrl", ['$scope', 'TextService', function($scope, TextService){
$scope.text = TextService.text;
}]);
然后我尝试显示 $scope.text,但它不起作用。 (我在 html 中分配了控制器)
<div class="content">
<h1>{{text}}</h1>
</div>
我想我需要使用一些辅助函数,因为 TextService 是异步的。我很想了解如何使它工作以及为什么它现在不起作用。在服务中包装 $http 调用是否是一个好的结构?
【问题讨论】:
-
text属性实际上存储了数据。您应该使用TextService.text而不仅仅是TextService。
标签: javascript angularjs http angularjs-http