Contrast between legacy and modern variables within angular

Trying to compare an old value in a <td> with the new value entered by the end user. Using ng-blur to detect when there is focus out of the field rather than calling the function, but the simple logic doesn't work.

This table structure:

<main ng-controller="mainCtrl">
    <table class="table table-bordered table-hover" ng-controller="tableCtrl">
        <p ng-model="old">{{old}}</p>
        <thead>
        <th>user name</th>
        <th>script name</th>
        <th>cron format<span class="glyphicon glyphicon-question-sign"  data-toggle="tooltip" data-original-title="Min|Hour|Day Of Month|Month|Day Of Week"></span></th>
        </thead>
        <tbody ng-repeat="(user_id,script_id) in data">
        <tr ng-repeat="(script_id, cron_format) in script_id">
            <td class="userName">{{user(user_id)}}</td>
            <td class="scriptName">{{script(script_id)}}</td>
            <td class="cronFormat"><input type="text" ng-model="cron_format" ng-blur="saveCron(user_id, script_id, cron_format)"/></td>
        </tr>
        </tbody>
    </table>

The comparison method :

$scope.old = $scope.cron_format = "";

$scope.saveCron(user_id, script_id, cron_format) {
    if ($scope.old == $scope.cron_format) {
        return; //value was unchanged
    }
        $.post("updateCronChange.php", "user_id=" + userId + "&script_id=" + scriptId + "&cron_format=" + cronFormat, function (data) {
            alert('cron format changed to:' + cronFormat);
        });
    $scope.old = $scope.cron_format;
}); 

The function executes each time the field is out of focus. Unsure about what's missing.

Answer №1

To keep track of the old value in each iteration of the ng-repeat, you can utilize ng-init and then compare it in a function:

<tr ng-repeat="row in data" ng-init="oldValue = row.value">

When calling the function:

ng-click="compareValues(row.id,row.name,row.value,oldValue)"

Inside the function definition:

$scope.compareValues = function(id, name, value, oldValue){
        console.log("Old Value: " + oldValue);            
        console.log("New Value: " + value);            
        if (oldValue != value) {
            // perform action
        }
    }

Check out this Fiddle for reference.

Answer №2

It seems like you want to preserve an old value and display it. One approach is to modify the code as follows:

if ($scope.old != $scope.cron_format) {
   $.post("updateCronChange.php", "user_id=" + userId + "&script_id=" + scriptId + "&cron_format=" + cronFormat, function(data) {
     alert('cron format changed to:' + cronFormat);
  });
  $scope.old = $scope.cron_format;
}

If you prefer, here is a practical example:

var test = angular.module('test', []);

test.controller('TestCtrl', ['$scope',
  function($scope) {
    $scope.myModel = '';
    $scope.old = '';
    $scope.getNewValue = 'false'

    $scope.saveModel = function(value) {
      if ($scope.old != value) {
        $scope.getNewValue = 'true';
        $scope.old = value;
        $scope.myModel = '';
        // You can include your post request here
      } else {        
        $scope.getNewValue = 'false';
      }
    };

  }
]);
.green {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app='test'>
  <div ng-controller="TestCtrl">Enter Some Text
    <input type="text" ng-model="myModel" ng-blur="saveModel(myModel)">
    <p>Old Value - {{old}}</p>
    <p>Current Value - {{myModel}}</p>
    <p class="green">Get New Value - {{getNewValue}}</p>
  </div>
</div>

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

Dynamic Rendering of Object Arrays in Table Columns using JavaScript

In the process of developing an appointment slot selection grid, I have successfully grouped all appointments by dates. However, I am facing challenges in displaying this array of Objects as a clickable grid with columns. The current output can be viewed h ...

What are the steps to retrieve raw messages from Gmail using Node.js?

I'm attempting to retrieve the complete email message data, including body content, using the raw format option specified in the gmail api reference. Unfortunately, it doesn't appear to be functioning correctly. Here is the code I'm using: ...

What is the best way to position the navbar above all the other text content?

I'm experiencing an issue where the navbar is not appearing on top of all the text/buttons. How can I adjust it so that the navbar appears on top? Thank you. https://i.sstatic.net/59M2l.png [Codepen](https://codepen.io/turbo0/pen/NWBMNQr) ...

What steps can I take to deactivate input and stop it from being accessible on the browser?

insert image description Is there a method to block users from accessing disabled input fields in the browser? Any recommendations or solutions would be greatly appreciated. Vuejs is utilized within my project. Implementing this feature serves as a secu ...

Having trouble with serving static files on elastic beanstalk

My angular app works perfectly fine on localhost, but on beanstalk it's not serving all my files. Only index.html and styles.css are found and served, both in a folder called public in the root directory. The build file is located at /build/build.js a ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

CSS for when the mouse hovers over an element

Two php files and a js file are involved in this scenario. The issue at hand is that when the div is clicked, it navigates to a new page with an appended # to the URL, causing it to scroll to the specified comment ID. However, instead of scrolling to the c ...

Implementing dynamic routes with Nuxt.js

I encountered an issue while working on deploying my Nuxt.js page to Netlify. Everything went smoothly except for the dynamic pages I had created. Below is a snippet from my nuxt.config.js file: import axios from 'axios' let dynamicRoutes = () = ...

Adjust the size of an input field in jquery or javascript based on user input

Ensure that an input text box can only contain a maximum of 13 numbers, but if the user enters a 14th number as a decimal point, then allow up to 16 numbers. HTML: <input type="text" maxlength="15" onkeyup="checkCurrency(this)"/> Script: func ...

Creating a versatile protractor framework to streamline multiple project implementations

There's a concept in the works for creating a 'protractor core' that will be utilized by various projects for UI testing. Currently, I have an Angular project called 'project1' with e2e tests (cucumber-protractor-typescript) that c ...

Retrieve a collection of items based on their data-id attribute

I need to create a list of label elements with data-id attributes. I will use the values from these labels to set images on the main container. The function changeimage is returning a nodelist with null elements, but I am not sure why this is happening. ...

Proper techniques for testing an AngularJS Controller Function

Recently, we integrated jasmine tests into our AngularJS project and I have a query: We are looking to write tests for this controller function: $scope.deleteClick = function () { $scope.processing = true; peopleNotesSrv.deleteNote($scope ...

Button generated using JavaScript is not triggering the onclick event

I've recently created a function that inserts a button inside a leaflet popup, like this: function popUp(feature, json){ myFunction("Cat").outerHTML }; Below is the actual function responsible for generating the button: function myFunct ...

Is there an issue with Vue-router 2 where it changes the route but fails to update the view

I am currently facing an issue with the login functionality on a website that utilizes: Vue.js v2.0.3 vue-router v2.0.1 vuex v0.8.2 In routes.js, there is a basic interceptor setup router.beforeEach((to, from, next) => { if (to.matched.some(record ...

Despite Nodejs's efforts, it was unable to successfully populate the user

I have been able to successfully reference and store other documents in my mongodb database as objectids for my application. However, I am facing an issue with the .populate method not working as expected. Below is the code snippet that I am using for po ...

Transforming a canvas into a div element

Hey there, I'm looking to swap out one canvas for another but I'm not sure how it will look on the browser. Any help would be greatly appreciated. <div id="juego"> <canvas width="203" height="256" id="1" class="bloque"></canvas& ...

The MongoDB operator that checks for multiple values within a specified field

I created a table with the following values: [ { id: 1, name: "abc" }, { id: 2, name: "lmn" }, { id: 3, name: "xyz" } ] My query includes $in as follows: { id: { $in: [ 2, 3, 1 ] } } I am hoping for the output to be in this or ...

Trouble arises when dynamic parameters fail to function post building in Nuxt

In my Nuxt project set to "spa" mode, I am facing an issue with a URL containing a dynamic parameter /shop/:product, which could have various values such as: /shop/ipad-128gb-rose-gold /shop/subway-gift-card /shop/any-string and so on. This ...

RequireJS - Enabling the loading of multiple module instances

I am working on a custom RequireJS plugin that needs to create a new object instance every time it is called. For illustration purposes, consider the following: define("loader", { load: function(name, req, onload, config) { var instance = GlobalGet ...