Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an extra object is needed? [duplicate]

I'm checking the Angular Bootstrap UI, especially the service $modal and noticed an interesting thing.

In their sample here 'http://plnkr.co/edit/E5xYKPQwYtsLJUa6FxWt?p=preview' in the controller that gets attached to the popup window they have enclosed the selected item into another inner property

$scope.selected = {
   item: $scope.items[0]
};

instead of having just

$scope.selected = $scope.items[0];

and indeed their code works as expected while my version does not.

Why is this needed? What's the JavaScript gotcha here?

Thx

like image 800
Eugen Avatar asked Nov 11 '22 16:11

Eugen


1 Answers

They're nesting the property because they want to do this in the modal:

<li ng-repeat="item in items">
    <a ng-click="selected.item = item">{{ item }}</a>
</li>

ng-repeat creates a child scope for each <li> (the modal is creating a child scope as well); if you'd have $scope.selected = $scope.items[0];, setting selected from the ng-click would set the property in the child scope, but not the parent scope (which is what you want in that example). Also see my answer here. In the case of

$scope.selected = {
    item: $scope.items[0]
};

the change will affect the parent scope's selected object.

like image 83
Lars Höppner Avatar answered Nov 14 '22 23:11

Lars Höppner