我有一项服务,可以在控制器和控制器之间共享数据,以便在我的应用程序中处理$ http请求。我使用带有ng-repeat的列表来显示 数据,目前在服务上有硬编码的JSON数据。我计划修改硬编码方法,使用$ http.post从服务器获取数据,我得到了数据,但我的列表没有更新。我试过添加$ timeout但仍然没有运气。
这是我的代码:
app.service("Storage", function ($rootScope, $http, $q) {
var predicate = 'name';
var reverse = false;
var content = this;
content.items = [];
content.filteredItems = [];
return {
requestData: function() {
var deferred = $q.defer();
var data = $.param({
json: JSON.stringify({
req_type: 'type_1',
reg_name: 'name_2'
})
});
$http.post("http://yourdomain/json.php", data)
.success(function(data, status) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
},
setContent : function(data){
content.items = data;
},
getContentItems : function () {
return content.items;
}
}
});
控制器:
app.controller('MainController', function($scope, $window, $filter, $timeout, $http, Storage) {
$scope.predicate = null;
$scope.reverse = null;
this.items = null;
Storage.requestData().then(function(data) {
Storage.setContent(data);
$timeout(function(){
$scope.predicate = Storage.getPredicate();
$scope.reverse = Storage.getReverse();
this.items = Storage.getContentItems();
});
//$scope.$apply();
console.log('After11 : ' + JSON.stringify(Storage.getContentItems()));
});
});
答案 0 :(得分:1)
你在这一行犯了错误:
this.items = Storage.getContentItems();
这个!===控制器这个
我始终在控制器顶部创建mv
变量,并使用mv
代替this
来避免此错误。
angular
.module('app', [])
.service('Storage', function($http, $q, $timeout) {
var content = this;
var items = [];
this.requestData = function() {
var deferred = $q.defer();
//TODO Some http request
$timeout(function() {
deferred.resolve(['A', 'B', 'C']);
}, 1000);
return deferred.promise;
};
this.setContent = function(data) {
items = data;
};
this.getContentItems = function() {
return items;
};
})
.controller('MainCtrl', function(Storage) {
var mv = this;
mv.items = [];
Storage.requestData().then(function(data) {
Storage.setContent(data);
mv.items = Storage.getContentItems();
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
</head>
<body ng-app="app">
<ul ng-controller="MainCtrl as mv">
<li ng-repeat="item in mv.items" ng-bind="item"></li>
</ul>
</body>
</html>