如何从AngularJS中的JSON文件更新?

时间:2017-04-22 20:35:00

标签: angularjs json

我有一个表单,当用户编辑表单并更新表单时。但是,我不想从app.js抓住它。相反,我想从像#34; app.json"这样的文件中抓取。

  

这是我的代码:

    <!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.3.6" 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;
    };

}]); 

1 个答案:

答案 0 :(得分:1)

您可以使用$ http get请求从json文件获取数据,并按如下所示更新变量

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

<强> DEMO