在AngularJS中,我正在尝试从JSON数据制作和编辑TreeView。我想从JSON获取nodevalue并使用表单进行编辑。编辑时,原始JSON应立即更改。我为此创建了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数据将是一个巨大的,我不知道如何更新它而不使用变量。请帮忙。
答案 0 :(得分:2)
您可以使用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
每次按键都会{。}}。