TL;DR skip to bottom-->
I found an ng-class example on Codepen, here (important code reproduced below).
In it, the author creates a simple menu bar that highlights the active item. Pretty standard. However, I thought the way he did it was funny, so I modified it to what made more sense to me and surprisingly it broke.
The author creates his view like this:
...
<div>Change the active menu item:
<input ng-model="states.activeItem" />
</div>
<ul class="navigation">
<li ng-repeat="item in items" class="item" ng-class="{'active': item.id == states.activeItem}" ng-click="states.activeItem=item.id">{{item.title}}</li>
</ul>
....
while his controller looks like
app.controller('NavigationController', function ($scope) {
// Must use a wrapper object, otherwise "activeItem" won't work
$scope.states = {};
$scope.states.activeItem = 'item1';
$scope.items = [{
id: 'item1',
title: 'Home'
}, {
id: 'item2',
title: 'Public Rooms'
}, {
id: 'item3',
title: 'My Rooms'
}];
});
To me, I thought it would be easier to skip the states
variable and just have a
$scope.activeItem
so I changed the controller to that, and changed the view to
<div>Change the active menu item:
<input ng-model="states.activeItem" />
</div>
<ul class="navigation">
<li ng-repeat="item in items" class="item" ng-class="{'active': item.id == activeItem}" ng-click="activeItem=item.id">{{item.title}}</li>
</ul>
However it now doesn't work.
So it seems for some reason Angular needs to store these variables in a new object. But why?
TL;DR: Here are both Codepens:
The Original (works great)
Mine (doesn't work)
Why doesn't mine work?