Valor_ Valor_ - 2 months ago 23
AngularJS Question

Dynamical ng-model in ng-repeat is undefined

I need help with dynamically generated models inside ng-repeat. I have a HTML with ng-repeating table rows. Each row has an option to update image name and price with update button.

HTML

<tr role="row" class="odd" ng-repeat="i in slideShowImages track by $index">
<td>
<img ng-src="{{i.thumb_path}}" width="100px" height="auto" >
</td>
<td>
<div class="form-group">
<input type="text" name="imageName" ng-model="i.imageName[$index]"
class="form-control" id="imageName" required>
</div>
</td>
<td>{{i.date_taken | myDate}}</td>
<td>
<div class="form-group">
<input type="text" name="imagePrice" ng-model="i.imagePrice[$index]"
class="form-control" id="imagePrice" required>
</div>
</td>
<td>
{{i.position}}
</td>
<td>
<a ng-click="updateImage(i.id_thumb, $index)">
<button class="btn btn-block btn-success">Update</button>
</a>
</td>
<td>
<a ng-click="deleteImage(i.id_thumb, $index)">
<button class="btn btn-block btn-danger">Delete</button>
</a>
</td>
</tr>


And this is my controller function which is trying to get the values

$scope.updateImage = function(id, $index){
$scope.models = {};
console.log(id);
console.log($index);
console.log($scope.i.imageName[$index]);
console.log($scope.i.imagePrice[$index]);
};
// result of console logs
4
0
angular.js:13550 TypeError: Cannot read property 'imageName' of undefined
at Scope.$scope.updateImage (locationsCtrl.js:243)
at fn (eval at compile (angular.js:14432), <anonymous>:4:486)
at expensiveCheckFn (angular.js:15485)
at callback (angular.js:25018)
at Scope.$eval (angular.js:17229)
at Scope.$apply (angular.js:17329)
at HTMLAnchorElement.<anonymous> (angular.js:25023)
at HTMLAnchorElement.dispatch (jQuery-2.1.4.min.js:3)
at HTMLAnchorElement.r.handle (jQuery-2.1.4.min.js:3)


Guess i'm doing something wrong, based on error that imageName and imagePrice can't be undefined. I hope you guys can help me. If you need any additional information's please let me know and i will provide. Thank you in advance

Answer

You had ng-repeat with i in slideShowImages which says that, on each iteration i will have current element of collection over the UI only(not in controller scope). So you can not get $scope.i value inside controller. You have to pass that value from updateImage as a parameter like ng-click="updateImage(i)". Then you can play with i object which is available on UI.

HTML

<td>
    <a ng-click="updateImage(i)">
        <button class="btn btn-block btn-success">Update</button>
    </a>
</td>
<td>
    <a ng-click="deleteImage(i, $index)">
        <button class="btn btn-block btn-danger">Delete</button>
    </a>
</td>

Controller

$scope.updateImage = function(i){
    console.log(i.imageName);
    console.log(i.imagePrice);
};
Comments