Get and update json using angular.js

前端 未结 3 1442
星月不相逢
星月不相逢 2020-12-15 01:54

I am very new to angular.js and am having some trouble with a seemingly simple task.

I need to get the json below from a json file on a website, then place the keys

相关标签:
3条回答
  • 2020-12-15 02:26

    You can't modify files on the server, $http.post doesn't work that way.

    0 讨论(0)
  • 2020-12-15 02:28

    You can not use $http.post in angular to save. Client side code can not and should not save to the server. You can imagine how DANGEROUS this would be.

    Instead... you can setup a NodeJS/Express (or whatever) to accept the JSON data in an $http.post. Then you can write the data to a file using a server-side platform. However, I would recommend not saving data to a .json file on the server. I make my .json files read-only and mainly used to populate static variables. You should look into storing these types of documents in a document store like CouchDB or MongoDB.

    0 讨论(0)
  • 2020-12-15 02:31

    Here's something to get you started. I changed your json to something that I believe is more appropriate, but you can change it back for your purposes if you wish. If you do use your json, you'll have a problem with ng-repeat finding duplicate values and you'll need to use track by $index to fix it. See this post (click).

    Live demo here (click).

    var app = angular.module('myApp', []);
    
    /* $http ajax calls really belongs in a service, 
    but I'll be using them inside the controller for this demo */ 
    
    app.controller('myCtrl', function($scope, $http) {
      /*$http.get('path/to/json').then(function(data) {
        $scope.languages = data;
      });*/
      //inputting json directly for this example
      $scope.languages = [        
        {name:"English", value:0},
        {name:"Spanish", value:1},
        {name:"German", value:3},
        {name:"Russian", value:2},
        {name:"Korean", value:1}
      ];
      $scope.save = function() {
        /*$http.post('path/to/server/file/to/save/json', $scope.languages).then(function(data) {
          $scope.msg = 'Data saved';
        });*/
        $scope.msg = 'Data sent: '+ JSON.stringify($scope.languages);
      };
    });
    

    You'll want to read the information in this post (click) if you want to avoid wrapping your markup in an extra div.

    <form>
        <div ng-repeat="lang in languages">
          <label>{{lang.name}}</label>
          <input type="range" min="0" max="4" ng-model="lang.value" >
        </div>
        <button ng-click="save()">Save</button>
        <p>{{msg}}</p>
    </form>
    
    0 讨论(0)
提交回复
热议问题