I have implemented a feature on my page where users can add objects to an array. These objects are then displayed on the page along with links for editing each item in the array.
Each added item is assigned a primary key, allowing users to edit it later even if its position in the array changes due to deletion or reordering.
The functionality for adding items is working correctly, but I am encountering issues with the edit behavior. Whenever I update the ng-model that the form controls are bound to, the form does not display the record intended for editing. I suspect this might be related to $scope handling, although I have already declared the model within the parent $scope to address this.
To access the Plunker example, click on the following link: 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;
}
};
}]);
Thank you for your help!