删除里面的一些数据后更新json

时间:2017-05-13 11:42:58

标签: angularjs json

我尝试学习角度。目前,我已经从JSON获取数据(我使用本地JSON)。我尝试从JSON中删除一个数组,它的工作原理但是在我刷新页面后,删除的数组再次返回。删除数组后如何更新JSON?

customer.html

<tr ng-repeat="experience in experiences">
            <td>{{experience.no}}</td>
            <td>{{experience.name}}</td>
            <td><button ng-click="deleteItem(experience)" class="btn btn-danger">-</button></td>
</tr>

main.js

 resolve:{
        experiences:['$http',function($http){
        return $http.get('scripts/customer.json').then(function(response){
            return response.data
            })
        }]
    }

客户json

[
  { 
    "no":1,
    "name": "Sarah",
  },
  {
    "no":2,
    "name": "Tommy",
  }
]

customerCtrl.js

angular.module('app').controller('customerCtrl',['$scope','experiences',function($scope,experiences){
$scope.experiences= experiences;


$scope.deleteItem =function(experience){
    var index = $scope.experiences.indexOf(experience);
    alert("Deleting DATA: "+ index);
    $scope.experiences.splice(index,1);
};

}]);

1 个答案:

答案 0 :(得分:0)

您尝试使用javascript将数据存储在文件中,这被认为是不安全的,然后很难实现。

我建议您改用LocalStorage。以下是您可以在控制器中使用的服务示例(未经测试)

localstorage服务

angular.module('app').service('LocalStorage', function(){

 return {
  save: function(data) {
   localStorage.setItem('data',data);
  }, 
  get: function(){
   return localStorage.getItem('data');
  }
 };
});

<强>控制器

// notice that I injected LocalStorage in controller
angular.module('app').controller('dataPengalamanCtrl',['$scope','experiences',function($scope,experiences, LocalStorage){
$scope.experiences= experiences;


$scope.deleteItem =function(experience){
    var index = $scope.experiences.indexOf(experience);
    alert("Deleting DATA: "+ index);
    $scope.experiences.splice(index,1);

    // First transform you're json to a string    
    var stringifiedData = JSON.stringify( $scope.experiences);

    // from there we save data to localStorage
    LocalStorage.save(stringifiedData );
};

// if you need, you can load data using :
$scope.data = LocalStorage.get();

不要忘记先将你的json保存在localstorage中,例如使用类似这样的文件:

<强> init.js

var json = [
  { 
    "no":1,
    "name": "Sarah",
  },
  {
    "no":2,
    "name": "Tommy",
  }
];

var strData = JSON.stringify(json);
localstorage.setItem('data', strData);

修改 如果你想使用像myjson.com这样的远程服务器

假设您已将您的json保存在myjson.com上,并且网址为https://api.myjson.com/bins/8hghd则:

要检索您的json使用$http.get('https://api.myjson.com/bins/8hghd').success(/*...*/).error(/*..*/);

使用您的json作为数据更新您的json使用$http.put(语法取决于您的AngularJS版本,请参阅here

查看api文档:http://myjson.com/api