我的页面有一个表单,用于向数组添加对象。该数组显示在页面上,其中包含用于编辑数组项的链接。
当我添加项目时,我附上一个主键,以便以后能够编辑该项目,以防它被删除并且其数组索引被更改。
添加功能正在运行但编辑行为不起作用。当我更新表单控件绑定到的ng-model时,表单不会显示要编辑的记录。它可能是$ scope问题,但我在父$ scope中专门声明了模型以实现此目的。
这是一个吸虫: http://plnkr.co/edit/yDlPpFunxFLHPiI0kCdj?p=preview
<form ng-controller="formCtrl" novalidate ng-submit="submit()">
<input type="text" name="name" ng-model="student.name" placeholder="name">
<input type="number" name="age" ng-model="student.age" placeholder="age">
<input type="hidden" ng-value="pk">
<input type="submit">
</form>
<h1>students</h1>
<ul>
<li ng-repeat="item in students"><a href="#" ng-click="editStudent(item.pk)">{{item.name}}</a> - {{item.age}}</li>
</ul>
var myApp = angular.module('myApp',[]);
myApp.controller("myCtrl", ['$scope', function($scope ){
$scope.student = {};
$scope.pk = 1;
$scope.index = 0;
$scope.students = [];
$scope.editStudent = function (id) {
for (var i = 0; i < $scope.students.length; i++) {
console.log("comparing "+$scope.students[i].pk+ " & " + id);
if ($scope.students[i].pk == id ) {
console.log("editing pk nr.: "+ id);
$scope.student = {
name: $scope.students[i].name,
age: $scope.students[i].age
};
$scope.index = id;
}
}
};
}]);
myApp.controller("formCtrl", ['$scope', function($scope) {
$scope.submit = function () {
if ($scope.index === 0) {
$scope.students.push({
name: $scope.student.name,
age: $scope.student.age,
pk: $scope.pk
});
$scope.pk++;
$scope.student = {};
} else {
for (var i = 0; i < $scope.students.length; i++) {
if ($scope.students[i].pk == $scope.index) {
$scope.students[i] = {
name: $scope.student.name,
age: $scope.student.age,
pk: $scope.index
};
}
}
$scope.index = 0;
}
};
}]);
由于
答案 0 :(得分:0)
我所做的改变是:
$index
编辑您点击的项目时可用的ng-repeat
媒体资源。这是您的HTML
:
<div ng-app="myApp" ng-controller="myCtrl as ct">
<form novalidate>
<input type="text" name="name" ng-model="newStudent.name" placeholder="name">
<input type="number" name="age" ng-model="newStudent.age" placeholder="age">
<input type="hidden" ng-value="pk">
<input type="button" value="submit" ng-click="submit()">
</form>
<h1>students</h1>
<ul>
<li ng-repeat="item in students"><a href="#" ng-click="editStudent($index)">{{item.name}}</a> - {{item.age}}</li>
</ul>
</div>
您的JavaScript
文件:
var myApp = angular.module('myApp',[]);
myApp.controller("myCtrl", ['$scope', function($scope ){
$scope.newStudent = {};
$scope.students = [];
$scope.index = -1;
$scope.editStudent = function (index) {
console.log('Editing student: ' + $scope.students[index].name);
$scope.index = index;
$scope.newStudent = angular.copy($scope.students[index]);
};
$scope.submit = function () {
if ($scope.index < 0) {
$scope.students.push($scope.newStudent);
} else {
$scope.students[$scope.index] = $scope.newStudent;
}
$scope.newStudent = {
name: '',
age: ''
}
$scope.index = -1;
};
}]);
修改强>
我刚修改了编辑学生时的代码,使用angular.copy
以便在编辑时失去对$scope.students
数组的绑定,并且只有在您单击提交时才会应用更改按钮。