在 AngularJS 的 JSON 中添加、删除和更新特定数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34839697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:14:05  来源:igfitidea点击:

Add, Remove & Update specific data In JSON in AngularJS

angularjsjson

提问by Khilen Maniyar

I have pulled data from json file. Now its displayed over DOM. On HTML Page, I have three option 1) Edit Data 2) Delete Particular Data & 3) Add New Data.

我已经从 json 文件中提取了数据。现在它显示在 DOM 上。在 HTML 页面上,我有三个选项 1) 编辑数据 2) 删除特定数据 & 3) 添加新数据。

How to perform this using AngularJS Code? i.e. on editing name, it should update my JSON object. On Deleting row, it should delete that row in JSON data. and also If I click on Add New, then entered data will be added to JSON.

如何使用 AngularJS 代码执行此操作?即在编辑名称时,它应该更新我的 JSON 对象。在删除行时,它应该删除 JSON 数据中的该行。并且如果我单击“添加新”,则输入的数据将被添加到 JSON。

My Code is as below. Importing data through json file and displaying on DOM

我的代码如下。通过json文件导入数据并在DOM上显示

.controller('MainCtrl', function ($scope, $http) {
  $http.get('data/home.json').
    success(function(data, status, headers, config) {
      $scope.details = data;
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});  

Output of this code is correct as below image. enter image description hereJSON Object as below.

此代码的输出是正确的,如下图所示。 在此处输入图片说明JSON 对象如下。

    {   
   "status":"success",
   "adformat":[   
      {   
         "adformat_id":1,
         "name":"Format 1",
         "size":"300x250"
      },
      {   
         "adformat_id":2,
         "name":"Format 2",
         "size":"320x250"
      },
      {   
         "adformat_id":3,
         "name":"Format 3",
         "size":"320x480"
      }
   ]
}

采纳答案by ssuperczynski

I would do it like this:

我会这样做:

MainCtrl.js

主控件.js

(function () {
    'use strict';

    angular
            .module('app')
            .controller('MainCtrl', MainCtrl);

    MainCtrl.$inject = ['$scope', 'MainFactory'];

    function MainCtrl($scope, MainFactory) {

        $scope.details = MainFactory.details;

        function init() {
            MainFactory.get();
        }

        init();

        $scope.detailsModel = {
            "adformat_id": 1,
            "name": "Format 1",
            "size": "300x250"
        };

        $scope.add = function () {
            $scope.details.push($scope.detailsModel);
        };

        $scope.delete = function (index) {
            $scope.details.splice(index, 1);
        };

        $scope.edited = -1;
        $scope.editedModel = {
            "adformat_id": 0,
            "name": "",
            "size": ""
        };

        $scope.edit = function (index) {
            $scope.edited = index;
        };

        $scope.finishEdit = function (index) {
            $scope.details[index] = $scope.editedModel;
            $scope.edited = -1;
        };
    }
})();

MainFactory.js

主工厂.js

(function () {
    'use strict';

    angular
            .module('app')
            .factory('MainFactory', MainFactory);

    MainFactory.$inject = [];

    function MainFactory() {

        var self = this;

        self.details = [];
        self.get = $http.get('data/home.json')
                .then(function (response) {
                    self.details = response.data;
                }).catch(function (error) {
                    // log error
                });

        return self;
    }
})();

index.html

索引.html

<div ng-app="app">
    <div ng-controller="MainCtrl">
        <table>
            <tbody>
            <tr ng-repeat="details in detail">
                <!-- show-->
                <td ng-hide="edited === $index">{{detail.adformat_id}}</td>
                <td ng-hide="edited === $index">{{detail.name}}</td>
                <td ng-hide="edited === $index">{{detail.size}}</td>
                <td ng-hide="edited === $index">
                    <button ng-click="edit($index)">Edit</button>
                    <button ng-click="delete($index)">Detele</button>
                </td>
                <!-- Edit-->
                <td ng-show="edited === $index">{{detail.adformat_id}}</td>
                <td ng-show="edited === $index"><input type="text" ng-model="editedModel.name"></td>
                <td ng-show="edited === $index"><input type="number" ng-model="editedModel.size"></td>
                <td ng-show="edited === $index">
                    <button ng-click="finishEdit($index, editedModel)">Save</button>
                    <button ng-click="delete($index)">Detele</button>
                </td>
            </tr>
            </tbody>
            <tfoot>
            <tr>
                <td>
                    <button ng-click="add()">Add</button>
                </td>
            </tr>
            </tfoot>
        </table>
    </div>
</div>

It is just prototype, not tested, but it should help you to understand idea o two way binding in angular.

它只是原型,未经测试,但它应该可以帮助您理解角度双向绑定的想法。

回答by DILIP KOSURI

Here is my approach to this requirement. Let me know if any further improvement can be added. The entire code can be found at the below URL:

这是我对这个要求的处理方法。让我知道是否可以添加任何进一步的改进。整个代码可以在以下 URL 中找到:

Angular Save, Update and Delete

Angular 保存、更新和删除

The sample screenshots from the code can be found here...

可以在此处找到代码中的示例屏幕截图...

controller:


'use strict';

function MainController($scope, SharedService, ngDialog) {

  $scope.account_type_selected = "Savings";
  $scope.sharedService = SharedService;
  $scope.savingsMain = [];
  $scope.checkingsMain = [];
  $scope.addToCheckingsAccounts = {};
  $scope.addToSavingsAccounts = {};


  $scope.setAccountType = function (type) {
    if (type === "allAccounts") {
      $scope.showSavings = true;
      $scope.showCheckings = true;
    } else if (type === "savingsAccounts") {
      $scope.showSavings = true;
      $scope.showCheckings = false;
    } else if (type === "checkingAccounts") {
      $scope.showSavings = false;
      $scope.showCheckings = true;
    }
    $scope.account_type_selected = type;
  };

  $scope.$watch('savingsMain', function ($scope) {
    return $scope.savingsMain;
  });

  $scope.selectedAccountType = function (showAccount) {
    console.log(showAccount);
    if (showAccount === "Savings") {
      $scope.sharedService.accountType = "Savings";
    } else {
      $scope.sharedService.accountType = "Checkings";
    }
  };


  $scope.saveAccounts = function () {
    if ($scope.sharedService.accountType === "Savings") {
      $scope.addToSavingsAccounts = {
        "account_type": $scope.sharedService.accountType,
        "amount": $scope.sharedService.amount,
        "date": $scope.sharedService.date,
        "maturity": $scope.sharedService.maturity
      };
      $scope.showSavings = true;

      $scope.savingsMain.push($scope.addToSavingsAccounts);
    } else {
      $scope.addToCheckingsAccounts = {
        "account_type": $scope.sharedService.accountType,
        "amount": $scope.sharedService.amount,
        "bic": $scope.sharedService.BIC,
        "iban": $scope.sharedService.IBAN
      };
      $scope.showCheckings = true;
      $scope.checkingsMain.push($scope.addToCheckingsAccounts);

    }
    ngDialog.close();

  };

  $scope.deleteDataFromSharedService = function (accountType, item) {
    if (accountType === "Savings") {
      $scope.savingsMain = _.without($scope.savingsMain, _.findWhere($scope.savingsMain, { date: item }));
    } else if (accountType === "Checkings") {
      $scope.checkingsMain = _.without($scope.checkingsMain, _.findWhere($scope.checkingsMain, { bic: item }));
    }
  };

  $scope.closeDialog = function () {
    ngDialog.close();
  };

  $scope.accountTypeModel = [];


  $scope.prop = {
    "type": "select",
    "name": "account_type",
    "value": $scope.sharedService.accountType,
    "accountTypeData": ["Savings", "Checkings"]
  };

}
<form ng-controller="MainController">
  <div class="page-header">
    <h1>Angular-Save-Update-Delete</h1>
  </div>
  <div class="content-wrapper">
    <div class="sidebar">
      <table>
        <tbody>
          <tr>
            <td>
              <button ng-click="setAccountType('allAccounts')" ng-model="allAccounts" class="ng-pristine ng-untouched ng-valid ng-empty">All</button>
            </td>
          </tr>

          <tr>
            <td>
              <button ng-click="setAccountType('savingsAccounts')" ng-model="savingsMain" class="ng-pristine ng-valid ng-not-empty ng-touched">Savings</button>
            </td>
          </tr>
          <tr>
            <td>
              <button ng-click="setAccountType('checkingAccounts')" ng-model="checkingsMain" class="ng-pristine ng-untouched ng-valid ng-not-empty">Checkings</button>
            </td>
          </tr>
          <tr>
            <td>
              <button class="create-account-btn-class" 
              type="button" 
              ng-dialog="app/views/create-account-template.html" 
              ng-dialog-data="" 
              ng-dialog-class="ngdialog-theme-default" 
              ng-dialog-scope="this" 
              plain=false
              showClose=true
              closeByDocument=true
              closeByEscape=true
              ng-dialog-show-close="false">New Account</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="right-content">
      <div id="savingsTemplate" templateurl="app/views/savings.html" ng-show="showSavings" include-template=""></div>
      <div id="checkingsTemplate" templateurl="app/views/checkings.html" ng-show="showCheckings" include-template=""></div>

    </div>
  </div>


</form>