Getting the right AngularJS $scope within a controller for beginners

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.

Answer №1

The reason behind this issue is that the ng-repeat directive creates a new child scope, causing you to modify the isEditing variable within that specific scope. To resolve this problem, make sure to specify the controller in the assignment:

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

Feel free to check out this jsFiddle example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The challenge of having to manually refresh the browser each time an update is made using a put request in

When the user enters a name and number and clicks the add button, the new person's information is automatically added to the database. If the name already exists, a prompt will ask, 'name is already in the phonebook, do you want to update it with ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

How can I resolve the issue of Angular displaying "NaN" instead of a date when converting a date into a

There was an issue with the date format coming from the server, displaying "Thu Jan 07 2016 11:00:40 GMT+0530 (IST)". I managed to convert this date into a more readable format as "1/7/2016 11:00 am". However, my goal is to have the date displayed in mm/dd ...

How can I efficiently retrieve the "value" of a cookie and store it in a .txt file using Python?

Seeking to automate certain requests, I am currently using selenium's get_cookie function to extract cookies from a website. The retrieved cookie data is returned as a dict structured like this: {'domain': 'website-name-here', &a ...

How can we integrate this icon/font plugin in CSS/JavaScript?

Check out the live demonstration on Jsfiddle http://jsfiddle.net/hc046u9u/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materializ ...

Tips for combining all included files into one with Babel

My current project involves the use of Babel. Within my server.js file, I have the following line of code: import schema from "./data/schema"; The issue arises because data/schema.js is written in ES2015 syntax. After attempting to compile my server.js ...

Ways to block past dates on bootstrap date picker starting from the current date and how to prevent dates beyond 90 days in the future from being selected on the

I am currently facing an issue with disabling previous dates from the current date in my code. While the functionality works well for the "From Date" date picker, I am having trouble implementing the same restriction for the "To Date" date picker after 90 ...

Leveraging the power of Google Charts along with MySQL or

I've been working on this task for several days now and I'm still struggling to achieve the desired outcome. My goal is to dynamically create a column/bar chart using Google Charts, populated with data from my database. Here's my query: SE ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...

The Material UI export of 'useInsertionEffect' (imported as 'useInsertionEffect$1') was not located within the 'react' library while utilizing the Appbar component

https://i.sstatic.net/twJwh.png 1: https://i.sstatic.net/Y2Zdo.png**strong text**https://i.sstatic.net/twJwh.png While attempting to implement the Appbar component from Material UI, I encountered an unexpected error. ...

Generating a text input field with multiple lines

<!DOCTYPE html> <html> <body> <p>Press the button to generate a File Upload Button.</p> <button onclick="myFunction()">Click here</button> <script> function myFunction() { var x = document.createElemen ...

The `background-size` property in jQuery is not functioning as expected

I am facing the following issue: When I click on a div with absolute positioning, I want to animate its position, width, and height. In addition, I want to change the background-size using jQuery. However, the problem is that all CSS properties are updat ...

When using AngularJS to poll a $resource at regular intervals, the promise that is returned from the $resource call does not automatically get resolved

Let's get to the important details: When I link a $scope variable in my controller directly to a $resource, Angular takes care of promise resolution automatically and updates my view as soon as data is received from the service. However, I need to per ...

Displaying a loading animation within a specific div element

Is it possible to use jQuery to insert a div into another div? My goal is to replace the contents of one div with a loading div while waiting for an ajax call to return. <div id="content1">foo</div> <div id="content2">bar</div> < ...

Using Three JS to recycle the geometry of a previously imported object

Is there a way to efficiently re-use imported object geometries in Three JS without duplicating them in memory? I've tried writing a loader but it doesn't seem to update the geometry once loaded. var tmpGeo = geometries[ID]; if (!tmpGeo) { t ...

Selecting a dropdown value dynamically after a form submission in ColdFusion using jQuery

I created a basic form with the use of an onload function to populate market values by default. However, I encountered an issue where after selecting a market value from the drop-down list and submitting the form, the selected value does not stay selected ...

Below is a compilation of items found within the JavaScript object that include the data from the previous list

I am currently experiencing an issue where the values in the list of objects within some object only contain values from the last object. My goal is to assign scores to locations based on various criteria (which are stored in a separate list). To simplify ...

Instructions for including dependencies from a globally installed npm package into a local package

I've noticed that although I have installed a few npm packages globally, none of them are showing up in any of my package.json files. What is the recommended npm command to automatically add these dependencies to all of my package.json files? ...

"Clicking on AppBar MenuItem functions properly on desktop, but it does not work on mobile devices in Material UI using

Within my reactjs application that employs Material UI, I have a Appbar containing a dropdown menu positioned in the top right corner. On desktop, the onClick function for each MenuItem works as expected. However, on mobile devices, the function does not t ...

Embedded URL in dynamically created AJAX text

I created a search field that uses ajax/jquery to generate a list of users. Result: <li class="list-group-item"> <span class="glyphicon glyphicon-user"></span> <span class="badge addUserToGroup" data-user="{{ user.getId }}"&g ...