Add, Remove & Update specific data In JSON in AngularJS

后端 未结 2 1342
不思量自难忘°
不思量自难忘° 2021-02-10 13:52

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 per

2条回答
  •  梦谈多话
    2021-02-10 14:48

    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

    {{detail.adformat_id}} {{detail.name}} {{detail.size}} {{detail.adformat_id}}

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

提交回复
热议问题