When an AJAX request is successful in Angular, utilize the ng-hide directive

I've implemented a feature where double-clicking the name displays an input field, but I'm facing an issue with switching back after a successful put-request. Despite setting $scope.edit to false, it doesn't seem to work as expected. This is my first attempt at working with Angular today.

<ul>
    <li ng-repeat="customer in customers">
        <label>
            <input type="checkbox" ng-model="customer.selected"/>
        </label>
        <span ng-hide="edit" ng-dblclick="edit = true;">{{ customer.name }}</span>
        <label ng-show="edit">
            <input type="text" ng-model="customer.name" ng-keyup="editCustomer($index, customer, $event)"/>
        </label>,
        <small ng-bind="customer.created_at"></small>
        <button ng-click="deleteCustomer($index, customer)">-</button>
    </li>
</ul>

Controller:

$scope.editCustomer = function (index, customer, event) {
    // enter
    if (event.keyCode === 13) {
        $http.put('customers/' + customer.id, customer).success(function () {
            // update customer.name binding
            $scope.edit = false;
        })
    } 
    // esc, do nothing and revert
    else if (event.keyCode === 27) {
        $scope.edit = false;
    }
};

Is there a more efficient solution for handling this scenario?

Answer №1

The issue you are facing is a common one that arises when using ng-repeat. By default, ng-repeat creates an isolated scope for each item it iterates over. This means that trying to set a variable like edit inside the child scope created by ng-repeat won't affect the parent controller's scope.

To solve this problem, you should use an object to store the variable so that changes are reflected properly across scopes. You can find more information on this behavior in the following link: https://github.com/angular/angular.js/wiki/Understanding-Scopes

To update your HTML code accordingly:

<ul>
    <li ng-repeat="customer in customers">
        <label>
            <input type="checkbox" ng-model="customer.selected"/>
        </label>
        <span ng-show="!customer.edit" ng-dblclick="customer.edit = true;">{{customer.name}}</span>
        <label ng-show="customer.edit">
            <input type="text" ng-model="customer.name" ng-keyup="editCustomer($event)"/>
        </label>
    </li>
</ul>

Also, adjust your controller code as follows:

$scope.editCustomer = function (event) {
    var customer = this.customer;    
    // enter key pressed
    if (event.keyCode === 13) {
        $http.put('customers/' + customer.id, customer).success(function () {
            customer.edit = false;
        })
    } 
    // escape key pressed, revert back
    else if (event.keyCode === 27) {
        customer.edit = false;
    }
};

I hope this explanation and solution prove helpful to you!

Best regards,
SA

Answer №2

To display and hide your input, it is necessary to use both ng-hide and ng-show directives. It might seem illogical, but in my experience, this is the only way it functions correctly in my controller. There could possibly be a bug causing this behavior.

<label ng-show="edit" ng-hide="edit-hide">
  <input type="text" ng-model="customer.name" ng-keyup="editCustomer($index, customer, $event)"/>
</label>

// Display control
$scope.edit = true;
$socpe.edit_hide = false;

// Hide control
$scope.edit = false;
$scope.edit_hide = true;

Answer №3

<ul>
    <li ng-repeat="client in clients">
        <label>
            <input type="checkbox" ng-model="client.selected"/>
        </label>
        <span ng-show="!editing" ng-dblclick="editing = true;">{{ client.name }}</span>
        <label ng-show="editing">
            <input type="text" ng-model="client.name" ng-keyup="editClient($index, client, $event)"/>
        </label>,
        <small ng-bind="client.created_at"></small>
        <button ng-click="removeClient($index, client)">-</button>
    </li>
</ul>

Controller:

$scope.editClient = function (index, client, event) {
    // enter
    if (event.keyCode === 13) {
        $http.put('clients/' + client.id, client).success(function () {
            // update client.name binding
            $scope.editing = false;
        })
    } 
    // esc, do nothing and revert
    else if (event.keyCode === 27) {
        // $scope.editing = false;
    }
};

Remember to set the default value $scope.editing = false at the beginning of your controller.

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

Javascript if-else is malfunctioning

I am having difficulty running the code below which contains if statements. I have tried removing some parts of it, but still can't get the alert to show up. Any advice would be highly appreciated. Thank you. <!DOCTYPE html> &l ...

Convert HTML table data to JSON format and customize cell values

Hey there, I have a HTML table that looks like this: <table id="people" border="1"> <thead> <tr> <th>Name</th> <th>Places</th> <th>Grade</th> </tr> & ...

Ways to convert a JavaScript object's properties into JSON format

I am currently manually going through the properties of my javascript class to create JSON, as shown below. It feels cumbersome and I am looking to automate this process so that I don't have to make changes to the 'toJson' function every tim ...

Perform a calculation using data from one schema and store the result in a different schema within MongoDB using Node.js

var ItemSchema = new Schema({ name: {type: String}, size : {type: String}, price : { type: Number} }); var SizeSchema = new Schema({ sizeName: {type: String}, dimensions : {type: String} }); F ...

How to generate a dropdown menu using a deeply nested JSON array

I'm looking to create a series of drop-down lists based on the JSON array provided below. There will be five drop-down lists, and when I select an option in one list, the other four should populate accordingly. For example, if I choose "Hindi" in the ...

Opting out of accents in the Vue filter and utilizing the table filter feature provided by Bootstrap-Vue

I am currently utilizing the Bootstrap-vue Table for filtering purposes, and I require assistance in implementing a regex filter to exclude words or letters with accents. Here is the regex snippet: string.replace('/[áàãâä]/ui', 'a&apos ...

If a particular <td> element is present on the page, exhibit a unique <div>

I have a webpage with various HTML elements. <div class="alert">Your message was not sent.</div> <p class="pending">Email Pending</p> I would like to display the div.alert only if the p.pending is present. Is ...

Why isn't my lightbox able to read this specific property?

A gallery was created using both lightgallery and cycle2. Cycle is a carousel plugin while lightgallery is a lightbox gallery. Clicking on an image in the carousel opens it in the lightbox. Everything worked perfectly until a category in the carousel was ...

Update dynamically generated CSS automatically

Is there a way to dynamically change the CSS? The problem I'm facing is that the CSS is generated by the framework itself, making it impossible for me to declare or modify it. Here's the scenario at runtime: I am looking to target the swiper-pa ...

Issues with managing ajax response handlers

Just dipping my toes into the world of ajax and attempting to create a reusable ajax request function. According to Firebug, the request is successfully fetching the correct data from my php file. However, for some reason, the response isn't getting i ...

Using JavaScript, you can employ the .split() and .replace() methods on a string value to accurately extract the specific

I'm currently attempting to extract hashtags from a text string by splitting it and removing unwanted HTML tags. Despite my efforts, I haven't been able to achieve the desired outcome. I am seeking guidance on where I might be going wrong. Here ...

Tips on incorporating the Browserified npm package into an Angular controller

After spending countless hours searching for a solution to integrate Browserify with my project, I found myself struggling to find a tutorial or example that addressed my specific issue. Most resources focused on bundling code rather than demonstrating how ...

Prioritize moving the JavaScript onload handler to the end of the queue

I am looking to include a JavaScript file at the very end of footer.php using a WordPress plugin. I attempted to do this with the 'add_action' Hook, but found that it is adding the JavaScript code near the </body> tag. add_action('wp_ ...

What is the best way to apply index-based filtering in Angular JS?

I am working on a tab system using ng-repeat to display tabs and content, but I'm facing some challenges in making it work seamlessly. Below are the tabs being generated: <ul class="job-title-list"> <li ng-repeat="tab in tabBlocks"> ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

How can I create a computed field in TypeORM by deriving its value from other fields within the same Entity?

My goal is to implement a 'rating' field in my User Entity. Within the User Entity, there exists a relationship with the Rating Entity, where the User has a field called ratingsReceived that eagerly loads all Ratings assigned to that User. The & ...

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...