4

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.

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.

My Code is as below. Importing data through json file and displaying on 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 here JSON Object as below.

    {   
   "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"
      }
   ]
}
Khilen Maniyar
  • 2,519
  • 7
  • 31
  • 35
  • 2
    Have you tried anything? What's the specific problem you're facing? – JB Nizet Jan 17 '16 at 14:57
  • 3
    Try this module http://ng-table.com/#/editing/demo-inline It Is super easy tu use. But if you would like to use you own methods written in angular, let me know. I will post more code – ssuperczynski Jan 17 '16 at 14:59
  • if you need to save the javascript object `$scope.details` into JSON file, just use [$http.put](https://docs.angularjs.org/api/ng/service/$http#put) – Aprillion Jan 17 '16 at 15:00
  • 1
    delete is fairly easy ...see http://stackoverflow.com/questions/15453979/how-do-i-delete-an-item-or-object-from-an-array-using-ng-click/15454424#15454424 . Combine that with a call to server – charlietfl Jan 17 '16 at 15:56
  • @infaustus, Thanks for giving demo of ng-table. however, it's dealing with table row, but how to update and perform operation on JSON object. Once I have final JSON then I will call $http.put to save in my file. But prior to that I need final JSON file. – Khilen Maniyar Jan 17 '16 at 18:35

2 Answers2

2

I would do it like this:

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>

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

ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
0

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:

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>
DILIP KOSURI
  • 455
  • 5
  • 10