piuspbd piuspbd - 4 months ago 16
AngularJS Question

How to create a property inside ng-repeat scope

I'm trying to make an editable list of items. There is an editing mode of each list.

HTML:

<ul ng-controller="ItemCtrl">
<li ng-repeat="item in items">
<div class="edit-off" ng-hide="editMode">...</div>
<div class="edit-on" ng-show="editMode">...</div>

<button ng-click="toggleEdit()">Edit</button>
</li>
</ul>


JavaScript:

angular.module("app", [])
.controller("ItemCtrl", function($scope) {
$scope.items = [...]; // list of items
$scope.editMode = false;

$scope.toggleEdit = function() {
$scope.editMode = !$scope.editMode;
};
});


I know that this code isn't correct since I attached
editMode
to the controller scope, not to
ngRepeat
scope. With this code, whenever I click at any button, all items will turn into editing mode.

All I want is that every item has its own
editMode
property in its scope, so that I can edit them individually.

Answer

put your property on each item:

<ul ng-controller="ItemCtrl">
    <li ng-repeat="item in items">
        <div class="edit-off" ng-hide="item.editMode">...</div>
        <div class="edit-on" ng-show="item.editMode">...</div>

        <button ng-click="toggleEdit(item)">Edit</button>
    </li>
</ul>


angular.module("app", [])
    .controller("ItemCtrl", function($scope) {
        $scope.items = [...]; // list of items

        $scope.toggleEdit = function(item) {
            item.editMode = !item.editMode;
        };
    });