user7138913
user7138913

Reputation:

How to update from a JSON file in AngularJS?

I have a form where when the user edits the form and the form get updated. BUT, I don't want to grab it from app.js. Instead, I want to grab from a file like "app.json".

Here is my code:

    <!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="1.3.6" src="https://code.angularjs.org/1.3.6/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">

    <div ng-controller="myCtrl"> 



      <input type="text" ng-model="myObject.sitePostcode"/>
      <button ng-click='update()'>Update</button>

      <div>Current Value: {{productAttributes.CostRequirements[0].OriginPostcode}}</div>
    </div>

  </body>

</html> 

App.js

    var app = angular.module("myApp", []);

app.controller('myCtrl', ['$scope', function($scope){

    $scope.productAttributes = {
        "CostRequirements":[
            {
                "OriginPostcode": 'NWU2017',
                "BearerSize":100

            }
        ]
    }
    $scope.myObject = {  
        sitePostcode : $scope.productAttributes.CostRequirements[0].OriginPostcode 
    }; 

    $scope.update = function(){
        $scope.productAttributes.CostRequirements[0].OriginPostcode = $scope.myObject.sitePostcode;
    };

}]); 

Upvotes: 0

Views: 48

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

You can use the $http get request to get the data from json file, and update the variable as below

 $http.get('data.json').
  then(function(response) {
    $scope.productAttributes = response.data;
  });

DEMO

Upvotes: 1

Related Questions