AngularJS 使用表单编辑 JSON 数据

AngularJS Edit JSON data using forms

在 AngularJS 中,我试图从 JSON 数据制作和编辑 TreeView。我想从 JSON 获取节点值并使用表单对其进行编辑。编辑时,原来的 JSON 应该立即改变。我为此创建了下面的 plunkr,但不知道如何实现。

Plunkr

var app = angular.module('plunker', []);

app.directive('collection', function () {       
    return {
        restrict: "E",
        //replace: true,
        scope: {collection: '='},
        //controller: 'TreeController',
        //bindToController: true,       
        template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"         
    }
})

app.directive('member', function ($compile) {
    var linkerfunc = function(scope, element, attrs) {  
                    var collectionSt = '<collection collection="member.children"></collection>';
                    $compile(collectionSt)(scope, function(cloned, scope)   {                                           
                        element.append(cloned); 
                     });
                     scope.ShowDetailsFunc = function() {   
                       console.log('in function scope showdetails')
                        scope.ShowDetailsCtrlFunc(element,event);                     
                    } 
    }
    return {
        restrict: "E",
        //replace: true,
        scope: {member: '=', ShowDetailsCtrlFunc : '&'},
        template: "<li><span ng-click=ShowDetailsCtrlFunc($event)>{{member.NodeName}}</span></li>",     
        controller: 'MainCtrl',
        //controllerAs: 'MainCtrl',
        //bindToController: true,
        link: linkerfunc        
    }
})

app.controller('MainCtrl', function ($scope,$timeout) {     

    $scope.Intialfunc = function() { 
        $scope.testdata = []
        var myjsondata = JSON.parse('{ "NodeName": "Parent", "NodePath": "1", "children": [ { "NodeName": "mychild", "NodePath": "1.1", "children": [ { "NodeName": "chld1", "NodePath": "1.1.1", "children": [] } ] } ] }');
        $scope.testdata.push(myjsondata);
            //console.log($scope.testdata) //This one is showing
            $scope.changename = $scope.testdata[0].children[0].children[0].NodeName;    

        }   

    $timeout(function(){ $scope.Intialfunc(); }, 1000)

    $scope.ShowDetailsCtrlFunc = function(event) {
            console.log("in function ShowDetailsCtrlFunc"); 

            //event.stopImmediatePropagation(); 
      };
});

我尝试了 angular.copy,但这需要 $scope 变量中的 JSON 数据部分并按预期更新该变量。

但是我的 JSON 数据会很大,我不知道如何在不使用变量的情况下更新它。请帮忙。

您可以使用 ng-change 在输入更改时执行操作:

<input type="text" ng-model="changename" ng-change="inputChange()">

然后,只需在您的控制器中创建一个函数来更新您需要的内容即可:

$scope.inputChange = function() {
  // do stuff here
  $scope.testdata[0].children[0].children[0].NodeName = $scope.changename;
  // write object to JSON
  var JSONstring = $scope.testdata.toJSON();
}

我还建议查看 ng-model-options 并更改去抖动设置,这样您就不会经常 toJSON 每次击键。

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