jocarosa jocarosa - 4 months ago 59
AngularJS Question

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

this is my code:

//route

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

//my view file showAllMy.html:

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

<center><h3>{{titleMyAll}}</h3></center>

<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>
</div>

<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}}>
</li>

</ul>

</div>


//In my controller

$scope.trade=function(yesNo,index){

if(yesNo=='yes'){

$scope.MyRequests=$scope.MyRequests+1;

}else{

$scope.MyRequests=$scope.MyRequests-1;
}


console.log('log'+$scope.tradeLink[index])
//$scope.tradeLink[0]=!$scope.tradeLink[0];

}


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

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 = [];