编辑 更新 JavaScript 中的现有数组
edit update existing array in javascript
我正在制作用于学习目的的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;
}
}
这只是解决此类问题的算法。你必须稍微修改一下。
相关文章:
- 如何通过数组更新角度子范围
- 如何创建独立于数组更新的组件列表
- 使用数组更新完整日历
- 数组更新后的敲除绑定
- c3js - 使用 chart.load() 使用颜色数组更新图表颜色
- 猫鼬位置数组更新
- 如何使用新数组更新 dom-repeat 列表
- .click在Javascript中没有任何效果 - 应该基于数组更新两个元素
- Angular2 从后端服务中的数组更新视图
- 推送前的数组更新 - javascript
- 使用 ajax 使用 jquery 数组更新 mysql 数据库
- Javascript二维字符串数组更新值
- 如何将数组更新到firebase
- Meteor AutoForm:如何用子文档数组更新模式值
- 为什么当数组更新时,引用数组元素的n't是我的对象
- 从类型化数组更新svg路径
- 聚合物dom-repeat如何通知数组更新
- 什么时候改变子数组更新子数组vs.创建一个新的子数组?[JavaScript]
- 当Javascript中的数组更新时,如何使用PHP更新和插入数据库
- 使用修改后的数组更新对象属性值