使用ng-resource更新json文件

时间:2015-05-31 11:43:37

标签: javascript json angularjs factory ngresource

我是AngularJS的新手,我想更新我的 data.json ,但我有这些错误:

  

POST XHR http://localhost:8080/Jquery/data/users.json [HTTP / 1.1 404   Introuvable 6ms]

     

DELETE XHR http://localhost:8080/Jquery/data/users.json [HTTP / 1.1 403   Interdit 2ms]

  

“错误:JSON.parse:JSON之后出现意外的非空白字符   JSON数据第5行第5行的数据

我的代码是:

index.html:

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js"></script>
<script>
    var app = angular.module('myApp', ['ngResource']);

    app.factory('User', ['$resource',
                      function($resource){
                          return $resource('data/users.json/:userId', {userId:'@id'},
                            {
                                'update': {method: 'PUT'}
                            }
                          );
                      }
                    ]);

    app.controller('UsersCtrl', function ($scope, User) {


          $scope.users = User.query();

          $scope.validate=function(user) {
              user.$update();
          }
          $scope.delete=function(user) {
              user.$delete();
          }
          $scope.create = function (newUserName) {
              var user = new User();
              user.name = newUserName;
              user.$save();
              $scope.users.push(user);
          }
      });

</script>
<body ng-app="myApp" ng-controller="UsersCtrl">

        <ul>
              <li ng-repeat="user in users">
                <input type="text" ng-model="user.name" />
                <button ng-click="validate(user)">Valider</button>
                <button ng-click="delete(user)">Supprimer</button>
              </li>
        </ul>
Nouveau utilisateur :
    <input type="text" ng-model="newUserName" />
    <button ng-click="create(newUserName)">Créer</button>
 <li ng-repeat="use in user">
               {{ use.name}}
              </li>
</body>
</html>

data / users.json:

[
{"userId": 123,"name": "Utilisateur 1"}, 
{"userId": 456,"name": "Utilisateur 2"}, 
{"userId": 789,"name": "Utilisateur 3"}
]

有人有解决方案吗?

0 个答案:

没有答案