roscioli roscioli - 1 year ago 85
AngularJS Question

Get and update json using angular.js

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 (english, spanish, etc.) inside label tags in my html file, then load their corresponding values (0, 1, 3, 2, 1) into html range inputs.

The json file contains:


The html produced after loading the json should look like:

<input type="range" min="0" max="4" value="ENGLISH_VALUE_RETRIEVED_FROM_JSON_FILE" >
<input type="range" min="0" max="4" value="SPANISH_VALUE_RETRIEVED_FROM_JSON_FILE" >
<input type="range" min="0" max="4" value="GERMAN_VALUE_RETRIEVED_FROM_JSON_FILE" >
<input type="range" min="0" max="4" value="RUSSIAN_VALUE_RETRIEVED_FROM_JSON_FILE" >
<input type="range" min="0" max="4" value="KOREAN_VALUE_RETRIEVED_FROM_JSON_FILE" >
<input type="submit" text="Save">

Finally I want to hit Save on the form and have the values for the corresponding keys updated on the json file online.

What are all the files necessary (using MVC) to build this example? If your answer involves any code, can you please explicitly say which file to add the code to?

Thanks in advance!

m59 m59
Answer Source

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}
  $ = function() {
    /*$'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.

    <div ng-repeat="lang in languages">
      <input type="range" min="0" max="4" ng-model="lang.value" >
    <button ng-click="save()">Save</button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download