我是AngularJS的新手,我的第一个项目需要您的帮助。
我想从JSON加载数据并使用ng-repeat将其显示在表中,这实际上效果很好。但是我想允许用户通过重新加载JSON重新加载表中的数据。
因此,我首先加载页面。我得到了JSON,并且表格已满。然后,我编辑JSON文件并保存。当我单击重新加载按钮时,收到的数据与加载页面时获得的数据完全相同。我以为是缓存,所以我清理了浏览器缓存,并在get请求中设置了cache:false,但这是行不通的。
这是我的代码:
var routeApp = angular.module("app", ["ui.bootstrap", "ngRoute", "ngSanitize", "ngAnimate", "routeAppControllers"]);
routeApp.config(function ($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "/SCAP/scap/resources/templates/home.html",
controller: "ctrlHome"
})
.when("/dgroups", {
templateUrl: "/SCAP/scap/resources/templates/device-groups.html",
controller: 'ctrlDeviceGroups'
})
.when("/templates", {
templateUrl: "/SCAP/scap/resources/templates/templates.html",
controller: 'ctrlTemplates'
})
.otherwise({
redirectTo: '/home'
});
});
var routeAppControllers = angular.module('routeAppControllers', []);
routeAppControllers.controller('ctrlDeviceGroups', function ($scope, groupsService) {
$scope.dgroups = [];
var promise = groupsService.getGroups();
promise.then(function(data) {
$scope.dgroups = data;
});
$scope.reloadJSON = function() {
$scope.dgroups = [];
console.log("Cleaning all data...");
console.log("Reloading JSON");
var promise = groupsService.getGroups();
promise.then(function(data) {
$scope.dgroups = data;
console.log("New JSON loaded");
console.log(data);
});
}
}).service('groupsService', function($http, $q, $sce) {
var json_file = "json.json";
// Add to use that because it didn't trust the domain...
var trustedUrl = $sce.trustAsResourceUrl(json_file);
var deferred = $q.defer();
console.log("Loading JSON...");
$http(
{
method: 'GET',
url: trustedUrl,
cache: false
}).then(function(data) {
deferred.resolve(data.data);
});
this.getGroups = function() {
return deferred.promise;
}
});
这是HTML(我删除了无用的行):
<div ng-controller="ctrlDeviceGroups">
<button ng-click="reloadJSON()">Reload entire table</button>
<table>
<tbody>
<tr ng-repeat="item in dgroups">
<!--TD-->
</tr>
</tbody>
</table></div>
如果您对如何重新加载JSON和视图有任何想法,我将不胜感激。我还注意到,但这不是主题的主题,如果我在$ scope.dgroups中推送数据,则ng-repeat不会刷新。
先谢谢您
答案 0 :(得分:0)
将GET请求移至服务方法中:
app.service('groupsService', function($http, $sce) {
var json_file = "json.json";
// Add to use that because it didn't trust the domain...
var trustedUrl = $sce.trustAsResourceUrl(json_file);
this.getGroups = function() {
console.log("Loading JSON...");
var config = {
method: 'GET',
url: trustedUrl,
cache: false
};
return $http(config)
.then(function(response) {
return response.data;
});
};
});