编辑 更新 JavaScript 中的现有数组

edit update existing array in javascript

本文关键字:数组 更新 JavaScript 编辑      更新时间:2023-09-26

我正在制作用于学习目的的CRUD应用程序。我需要在单击编辑按钮时更新现有的 javascript 数组。但是,目前它不更新现有数组,而是创建新记录。下面是控制器的JS代码

对于添加屏幕,下面是控制器代码

.controller('addController', ['$scope','$location','$rootScope', function(scope,location,rootScope){
    scope.save = function (){
        scope.personName = document.getElementById('name').value;
        scope.personDesc = document.getElementById('desc').value;
        scope.person = {'name' : scope.personName, 'desc' : scope.personDesc};
        if(typeof rootScope.crew === 'undefined'){
            rootScope.crew = [];
        }
        rootScope.crew.push(scope.person);
        location.path("/");
    }
}])

对于编辑屏幕,以下是控制器的代码:-

.controller('editController',['$scope','$location','$routeParams','$rootScope', function(scope,location,routeParams,rootScope){
    var oldName = scope.crew[routeParams.id].name;

    document.getElementById('name').value = scope.crew[routeParams.id].name;
    document.getElementById('desc').value = scope.crew[routeParams.id].desc;
    scope.editSave = function(){
        scope.person = {
            'name' : document.getElementById('name').value, 
            'desc' : document.getElementById('desc').value
        }
        rootScope.crew.push(scope.person);
        location.path("/");
    }
}])

目前,我正在现有数组中添加记录而不是更新。

请建议

问题是您正在将新项目推送到数组。只需使用范围内的人员更新现有人员。

.controller('editController',['$scope','$location','$routeParams','$rootScope', function(scope,location,routeParams,rootScope){
    var person = scope.crew[routeParams.id]
    scope.person = {
        name = person.name,
        desc = person.desc
    };
    scope.editSave = function(){
        scope.crew[routeParams.id] = scope.person;
        location.path("/");
    }
}])

在您的编辑视图中,您将拥有以下内容:

<input type="text" id="name" ng-model="person.name"/>
<input type="text" id="desc" ng-model="person.desc"/>

还值得一提的是,不需要像document.getElementById这样的代码,因为 angular 会为你处理模型绑定,所以你不必使用 javascript 与 dom 进行交互。

你在数组中推送的每个对象都必须由一些对象标识,id.So 为你正在推送的 person 对象分配一个 id 属性。

现在来编辑.html

<tr ng-repeat="p in person">
{{p.name}}
//In button  I am passing id which I used in editing the person object
<button ng-click="edit(p.id)"></button> 
</tr>
//In controller
edit(id){
//firstly search for the person which is going to be updated
for(i=0;i<arrayInWhichYouArePushingData.length;i++)
  {   
     if(arrayInWhichYouArePushingData[i].id==id)
        {
         arrayInWhichYouArePushingData[i]=UpdatedData;
           break;
       }
  }

这只是解决此类问题的算法。你必须稍微修改一下。