0

I have problem with understanding how to show/hide element on page using controller.

There is a code with an example - you can check it by clicking "close edit" button (nothing happen):

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; // here I would like to close editing option but it doesn't work
      //$scope.items[index] = newValue; // in next step I would like to update "item" value with new one but it doesn't work 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 want to change value "isEditing" via controller. There is no problem to do it via HTML like that

ng-click="isEditing = !isEditing"

But code below doesn't work correctly in controller:

$scope.isEditing = false;

The purpose of it is to show/hide buttons/fields to provide new values.

After that probably there will be problem with update new values.

If you can explain - thanks a lot.

1 Answer 1

1

This is because ng-repeat create new child scope and you are changing isEditing variable in that scope. To fix it specify controller in assignment:

ng-click="appCtrl.isEditing = !appCtrl.isEditing"

Here is jsFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I tried also add new controller to ng-repeat, and it's also works: <tr ng-repeat="item in items" ng-controller="controlerInNgRepeat">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.