I am struggling to understand how to toggle the visibility of an element on a webpage using a controller.
Below is a code snippet with an example - you can test it by clicking the "close edit" button (nothing happens):
var appModule = angular.module('appModule', []);
appModule.controller('appCtrl', ['$scope',
function($scope) {
$scope.items = [1, 2, 3, 4, 5]
$scope.closeEdit = function(index, newValue) {
$scope.isEditing = false; // I want to close editing option here but it doesn't work
//$scope.items[index] = newValue; // Next, I want to update the "item" value with the new one but it's not working correctly
};
}
]);
table td:first-child,
input {
width: 100px;
}
table td {
border: 1px solid silver;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<table ng-controller="appCtrl">
<tr ng-repeat="item in items">
<td>
<div>
<span ng-hide="isEditing"> <!-- should hide when editing and update after it with new value -->
{{item}}
</span>
<input ng-show="isEditing" type="text" ng-model="newValue" placeholder="{{item}}" />
<!-- should show when editing -->
</div>
</td>
<td>
<button ng-hide="isEditing" ng-click="isEditing = !isEditing">OPEN EDIT</button>
<!-- should hide when editing -->
<button ng-show="isEditing" ng-click="closeEdit($index, newValue)">close edit</button>
<!-- should show when editing -->
</td>
</tr>
</table>
I am looking for a way to change the value of "isEditing" via the controller. It works fine if I do it directly in HTML like this:
ng-click="isEditing = !isEditing"
However, setting it in the controller as shown below does not work properly:
$scope.isEditing = false;
The purpose of this functionality is to toggle the visibility of buttons/fields to allow for input of new values.
In addition to that, there may be a problem with updating the new values. If anyone can provide an explanation, I would greatly appreciate it.