Santhosh K N Santhosh K N - 6 months ago 61
AngularJS Question

How to re-populate the Dynamic ng-model fields when value from ng-repeat in Angularjs using ionic framework

I'm using ionic framework to build an app. In my form i need to re-populate the dynamic ng-model input field. I refer " How to create Dynamic ng-model in Angular " to create the dynamic ng-model field. it works. But when i'm trying to re-populate that field it was not working (I need to perform CRUD opearation).

My HTML part is:

<div class="row header">
<div class="col col-40">Name</div>
<div class="col col-60">Marks</div>
</div>

<div class="row" ng-repeat="(key, user) in userList">
<div class="col col-40" ng-bind="user.name"></div>
<div class="col col-60">
<input type="text" name="actual_marks" ng-model="markscardData.actual_marks[user.user_id]" placeholder="Please enter the marks" />
</div>
</div>


My controller is like this

.controller('MarkscardAddCtrl', function($scope, $stateParams, $state, $http, $ionicPopup, baseUrl)
{
$scope.markscardData = {};


$http.get(baseUrl+"api_method=markscard.getUserList&api_version=1.0&app_key=12345& course_id="+course+"&subject_id="+subject+"& markscard_id="+markscard).then(function(response){
$scope.userList = response.data.responseMsg;
});
})


The JSON value in $scope.userList like this

[{"name":"Harshith","user_id":"249","actual_marks":"76","min_marks":"40","max_marks":"100"},{"name":"Nithin","user_id":"246","actual_marks":"60","min_marks":"40","max_marks":"100"},{"name":"Prathik","user_id":"247","actual_marks":"70","min_marks":"40","max_marks":"100"},{"name":"Ravee","user_id":"250","actual_marks":"80","min_marks":"40","max_marks":"100"},{"name":"Shivarama","user_id":"248","actual_marks":"90","min_marks":"40","max_marks":"100"}]


I need markscardData.actual_marks[user.user_id] repopulate when form is open in edit mode and it allow update also. I'm done this in my website http://demo.lekhanii.com (please refer this for understanding my problem. for login =>mobile number : demo0012, =>password:test1234. Then go to update markscard and select the dropdown) Please help me on this. Thanks in advance.

Answer

I assume you are losing data when you reload the page. This is happening because the dynamic ng-models are not actually bound in your controller. If you want to load actual marks from the JSON you received,

for(var i in userList){
    $scope.markscardData.actual_marks[userList[i].user_id] = userList[i].actual_marks;
}

put this line below $scope.userList = response.data.responseMsg;. This should initialize your dynamic models if applicable. Also, you will need to put these two declarations at the start: $scope.markscardData = {}; $scope.markscardData.actual_marks = []; Hope this works for you .. :)