user2156149 user2156149 - 18 days ago 10
Javascript Question

AngularJS ng-repeat and controllerAs

I using simple syntax to show, hide element in ng-repeat

<div ng-controller='MainController as vm'>
<ul>
<li ng-repeat="item in vm.items" ng-click="vm.showItem()">
{{item}}
<span ng-show="show">test</span>
</li>
</ul>




When i was using scope everythink worked fine

$scope.showItem = function(){
this.show=!this.show;
}


But same code with controllerAs doesn't work

vm = this;
vm.showItem = function(){
this.show=!this.show;
}


How can i access to show property of current item in ng-repeat?

Controller as http://plnkr.co/edit/Dbp5fO9OEpV6lFRySYUK?p=preview

$scope http://plnkr.co/edit/ptuySNRXSrA64K1IAng3?p=preview

Answer

Get the current this instance from the html like

 <li ng-repeat="item in vm.items" ng-click="vm.showItem(this)">

And use it in your controller

vm.showItem = function(_this){
   _this.show=!_this.show;
}

The problem you faced is the change of this context

Updated plunker http://plnkr.co/edit/pkxI68sGMXonDOA49EUq?p=preview

Comments