如何使用 AngularJS 对 JSON 数据执行添加、编辑和删除操作?

How to perform Add, Edit and Delete operations for JSON data using AngularJS?

我有 json 文件:

test.json: 

{
    "MyTest": [{
        "Main": {
            "static": {
                "name": "TestName1"
            },
            "dynamic": {
            "testkey01": "testkey01data",
            "testkey02": 40,
            "testkey03vals": [1, 1, 1]
        }}
    }, {
        "Main": {
            "static": {
                "name": "TestName2"
            },"dynamic": {
            "testkey01": "test01value",
            "testkey03": 10,
            "testflags": ["Test"]
        }}
    }, {
        "Main": {
            "static": {
                "name": "TestName3"
            },"dynamic": {
            "testkey01": "testkey01value for TestName3",
            "testnumber": 30
        }}
    }]
}

我想使用 AngularJS 对这个 json 数据执行添加、Edit/Update 和删除操作。

我做了以下事情:

index.html:

<!DOCTYPE html>
    <html>
      <head>
       <script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
       <script src="app.js"></script> 
      </head>
      <body ng-app="myApp">
        <div ng-controller="TestCtrl">
            <table>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Edit</th>
                  <th>Add</th>
                </tr>
              </thead>
              <tbody>
                <tr ng-repeat="(key, value) in myTestJson.MyTest" >
                  <td>{{value.Main.static.name}} </td>
                  <td><a ng-href="editName.html">Edit</a></td>
                  <td><button id="button1"  ng-click="add(value.Main.static.name)">Add</button></td>
                </tr>
              </tbody>
            </table>
        </div>
        <br><br>
        <br>
        <table border="1" class="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Delete</th>
            </tr>
          </thead>
          <tbody>
            <tr  ng-repeat="name in jsonNames"  >
              <td>{{name}}</td>
              <td><button id="button1" name="singlebutton" ng-click="delete(name)">Delete</button></td>
            </tr>
            <tr ng-hide="myTestJson.MyTest.length">
              <td colspan="3">
                <p>No Names</p>
              </td>
            </tr>
          </tbody>
        </table>
      </body>
    </html>

editName.html:

<!DOCTYPE html>
    <html>
      <title>Edit and Update JSON data</title>
        <div>
           <table><tbody>
                <tr ng-repeat="(key, value) in myTestJson.MyTest.Main.dynamic" >
                  <td><label>{{key}}: </label> 
            <input placeholder="" type="text" ng-model="value">
                   </td>
                    </tr>
                </tbody>
            </table>
            <button value="Update and Save" id="saveButtonId" ng-href="index.html" ng-click="finishEdit">Update/Save</button>
        </div>
    </html>

app.js:

var app = angular.module('myApp', []);
app.controller('TestCtrl',function($scope, $http ) {
     $http.get('test.json').success(function(response) {
        $scope.myTestJson = response;
       // console.log(JSON.stringify(response));

      $scope.add = function (){
        alert("add is called");
        //$scope.myTestJson.push($scope.jsonNames);
        $scope.myTestJson.push($scope.myTestJson, jsonNames);
      };
       $scope.delete = function (index){
        $scope.myTestJson.splice(index,1);
        alert("JSON Name is deleted");
      }
     $scope.saveUpdate = function (index) {
            $scope.myTestJson[index] = $scope.dynamiceditedModel;
            $scope.edited = -1;
        };
        //$scope.dynamiceditedModel=$scope.myTestJson;
    });
  });

一个。如果我单击 Add 按钮:然后应在我的第二个 table.

中添加相应的 JSON 名称数据

b。如果我点击 Edit 按钮:然后各自选择的 JSON 名称“dynamic”字段选项应该是 editable(在 editName.html 上)然后应该被保存单击 Update/Save 按钮(然后应将其重定向到 index.html)。

c。如果我点击 Delete 按钮:那么相应的 JSON 名称应该被删除。

我创建了Plnkr。我请求大家帮我解决这个问题,我该如何执行这些操作。提前致谢。

你那里有十亿个错误。你应该明确地从一些非常基础的东西开始,然后一个一个地尝试 :)。我们都在学习,练习需要时间,所以不要误会。

我修复了你的添加/删除错误,你可以在这里找到它的工作示例

http://plnkr.co/edit/fPjll5WqgrWCR00TUoaK?p=preview

更具体地说,我改变了什么:

var app = angular.module('myApp', []);
    app.controller('TestCtrl',function($scope, $http ) {
      // created new scope variabile
      $scope.table2 = [];
         $http.get('test.json').success(function(response) {
            // removed functions from this scopes, there is no reason for it
            $scope.myTestJson = response;
         });

          $scope.add = function (name){   
            // giving argument to this function
            // pushing it to new variabile instead of old one
            $scope.table2.push(name);
          };
           $scope.delete = function (name){
             // argument name you was sending was just name
             // you need to find index of it in array
             index = $scope.table2.indexOf(name);
             // and then splice it
             $scope.table2.splice(index,1);
          }
          $scope.saveUpdate = function (index) {
                // I didnt get to this..
                $scope.myTestJson[index] = $scope.dynamiceditedModel;
                $scope.edited = -1;
            };            
      });

在 html 中我更改了这个:

  // You had whole second table out of any controller
  <body ng-app="myApp" ng-controller="TestCtrl">

这是根据我们的讨论得出的答案。这可能会很长,因为我处理了所有文件并添加了它们,

首先,

index.html

<!DOCTYPE html>
<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.js"></script>

  <script src="app.js"></script>
  <script src="test.json"></script>
</head>
<body ng-app="myApp">    
  <ui-view></ui-view>    
 </body>

</html>

app.js

var app = angular.module('myApp', ['ui.router']);
    app.controller('TestCtrl',function($scope, $http,$state,$stateParams,filterFilter,$rootScope) {
        $rootScope.jsonNames = []
        $rootScope.filteredArray = []
        console.log($rootScope.myTestJson)         
        if($rootScope.myTestJson == undefined)
        {
            $http.get('test.json').success(function(response) {
                $rootScope.myTestJson = response;
            })
        }    
           // console.log(JSON.stringify(response));

          $scope.add = function (name){
            alert("add is called");
            //$scope.myTestJson.push($scope.jsonNames);
            $rootScope.jsonNames.push(name);
            console.log($rootScope.jsonNames)
          };
           $scope.delete = function (index){
            $rootScope.jsonNames.splice(index,1);
            alert("JSON Name is deleted");
          }

          console.log($stateParams.edit != undefined)
          if($stateParams.edit != undefined){
            console.log($rootScope)
            $rootScope.id = $stateParams.edit
          }
         $scope.saveUpdate = function (index) {
                console.log($rootScope.myTestJson)
                $state.go('home')
            };
            //$scope.dynamiceditedModel=$scope.myTestJson;

    });
    app.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'main.html',
            controller: 'TestCtrl',
        })
        .state('edit', {
            url: '/edit/:edit',
            templateUrl: 'edit.html',
            controller: 'TestCtrl',
        });

});

main.html

<div>
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Edit</th>
        <th>Add</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="(key, value) in myTestJson.MyTest" >
        <td>{{value.Main.static.name}} </td>
        <!-- <td>{{$index}} </td> -->

        <td><a ui-sref="edit({edit: $index})">Edit</a></td>
        <td><button id="button1"  ng-click="add(value)">Add</button></td>
      </tr>
    </tbody>
  </table>

  <br><br>
  <br><p>Second Table:</p>
  <table border="1" class="table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Delete</th>
      </tr>
    </thead>
    <tbody>
      <tr  ng-repeat="(key, value) in jsonNames"  >
        <td>{{value.Main.static.name}}</td>
        <td><button id="button1" name="singlebutton" ng-click="delete($index)">Delete</button></td>
      </tr>
      <tr ng-hide="jsonNames.length > 0">
        <td colspan="3">
          <p>No Names</p>
        </td>
      </tr>
    </tbody>
  </table>
</div>

edit.html

<title>Edit and Update JSON data</title>
  <div>
    {{myTestJson.MyTest[id].dynamic}}
     <table><tbody>
          <tr ng-repeat="(key, value) in myTestJson.MyTest[id].Main.dynamic  track by $index"  >
            <td><label>{{key}}: </label> 
      <input placeholder="" type="text" ng-model="myTestJson.MyTest[id].Main.dynamic[key]">
             </td>
              </tr>
          </tbody>
      </table>
      <button value="Update and Save" id="saveButtonId" ng-click="saveUpdate()">Update/Save</button>
  </div>

json文件原样

请集成这个,我会在你想要的地方解释。