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

Posted

技术标签:

【中文标题】在 AngularJS 中的 JSON 中添加、删除和更新特定数据【英文标题】:Add, Remove & Update specific data In JSON in AngularJS 【发布时间】:2016-04-22 17:41:03 【问题描述】:

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

如何使用 AngularJS 代码执行此操作?即在编辑名称时,它应该更新我的 JSON 对象。在删除行上,它应该删除 JSON 数据中的该行。如果我点击 Add New,那么输入的数据将被添加到 JSON。

我的代码如下。 通过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
    );
);  

此代码的输出正确,如下图所示。 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"
      
   ]

【问题讨论】:

你有没有尝试过?您面临的具体问题是什么? 试试这个模块ng-table.com/#/editing/demo-inline 它超级容易使用。但是,如果您想使用自己用 Angular 编写的方法,请告诉我。我会发布更多代码 如果您需要将javascript对象$scope.details保存到JSON文件中,只需使用$http.put 删除相当简单...见***.com/questions/15453979/…。将其与对服务器的调用结合起来 @infaustus,感谢您提供 ng-table 演示。但是,它处理的是表行,但是如何更新和对 JSON 对象执行操作。一旦我有了最终的 JSON,我将调用 $http.put 保存在我的文件中。但在此之前我需要最终的 JSON 文件。 【参考方案1】:

这是我解决此要求的方法。让我知道是否可以添加任何进一步的改进。完整的代码可以在以下网址找到:

Angular Save, Update and Delete

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>

【讨论】:

【参考方案2】:

我会这样做:

MainCtrl.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

(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

<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>

这只是原型,未经测试,但它应该可以帮助您理解 Angular 中的两种方式绑定的想法。

【讨论】:

以上是关于在 AngularJS 中的 JSON 中添加、删除和更新特定数据的主要内容,如果未能解决你的问题,请参考以下文章

在 AngularJS 中向 Json 数组添加函数

如何在angularjs的下拉列表中添加图像

AngularJS中的Zoomable网络图

从AngularJS中的文件中读取JSON

向 json-server 添加新对象; AngularJS

怎么删除json数据里的元素