jocarosa jocarosa - 1 year ago 143
AngularJS Question

I cant access $scope.variable[index] within ng repeat in angular

this is my code:


.config(['$routeProvider',function($routeProvider) {
.when('/allbooks', {
templateUrl: 'find/showAllMy.html',
controller: 'controlador'
}).when('/mybooks', {
templateUrl: 'find/showAllMy.html',
controller: 'controlador'
templateUrl: 'find/inputbook.html',

//my view file showAllMy.html:

<div id='containerMyBooks' ng-init='MyRequests=0; RequestsForMe=0; '>


<div id='containerbuttonsrequest'>
<button class='waves-effect waves-light btn'>Your Trade Request {{MyRequests}} </button>
<button class='waves-effect waves-light btn'>Trade Request for you {{RequestsForMe}}</button>

<ul ng-repeat='b in Books' ng-init='tradeLink[$index]=true'>

<li class='styleLi'>
<a class='stylelinktrade' ng-show='tradeLink[$index]' href='/#/{{titleMyAll}}' ng-click="trade('yes',$index)"><img class="styleimgtrade" src='../images/trade.png'>trade!</a>
<a class='stylelinktrade' ng-hide='tradeLink[$index]' href='/#/{{titleMyAll}}' ng-click="trade('no',$index)"><img class="styleimgtrade" src='../images/trade.png'>Cancel trade</a>
<img class='styleimgbook' src={{b.img}}>



//In my controller








I cant access to $scope.tradeLink[index] from the view, twrow an error in the navigator saying cannot read property 1 or indefined, how can i fix it?

Iso Iso
Answer Source

That’s because you never initialized tradeLink to an array. Adding tradeLink = [] in your top ng-init should fix your bug.

But that said, please refrain from using ng-init:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

Instead, remove all your ng-init usages (besides the one with ng-repeat which might be relevant) and add this in your controller:

$scope.MyRequests = 0;
$scope.RequestsForMe = 0;
$scope.tradeLink = [];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download