Enhance the appearance of specific form inputs upon modification of ng-model within the textfield using AngularJS

After asking a similar question multiple times, I've realized that the specifics of my query were not clear enough.

Let's say in my controller there is an object named "guy" of type person structured like this:

{"ID"        : "1234",
 "firstName" : "Bob",
 "lastName"  : "Michael",
 "phone"     : "555-555-5555",
}

(Please note that the actual object I'm dealing with is much larger than this example)

Imagine a webpage with a form and a search box. The form contains fields for each attribute in the "guy" object, as shown below:

<label for="inputFirstName"> First Name: </label>
<input type="text" id="inputFirstName" ng-model = "person.firstName">

<label for="inputLastName"> Last Name: </label>
<input type="text" id="inputFirstName" ng-model = "person.lastName">

<label for="inputPhone"> Phone Number: </label>
<input type="text" id="inputPhone" ng-model="person.phone">

When we search by an "ID" number on the page, the form gets filled with the corresponding data from the object. Additionally, there is an "import" button on the page. Clicking this button imports a person object into the controller with all attributes identical to "guy" except firstName is now "Dan" and phone is now "111-111-1111". The "guy" variable is then assigned to this newly imported object, effectively updating the object with these changes. These changes are immediately reflected in the form.

I want to be able to visually highlight the fields that have been modified once the import button is clicked. However, my attempts so far have been unsuccessful. I tried something like this:

<label for="inputFirstName" 
        ng-class = "{ 'newCSS' : !!hasChanged }"> 
    First Name: 
 </label>
 <input type="text" 
        id=inputFirstName" 
        ng-model="person.firstName" 
        ng-change = "hasChanged = true">

But this approach only detects manual changes made in the text box, not changes triggered by clicking the import button. When I raised this issue before, someone suggested using $watch in this way:

Controller function demoCtrl ($scope) {

$scope.$watch('myModel', function (newValue, oldValue) {
    if (newValue) {
       $scope.hasChanged = true;
    }
 }, true);

$scope.changeMyModel = function () {
   $scope.myModel = 'wonderful';
 };

}

HTML

  <label for="stuff" ng-class="{ 'newCSS' : !!hasChanged }">Stuff</label>
  <input type="text" id="stuff" ng-model="myModel" ng-change="hasChanged = true">

  <button ng-click="changeMyModel()">change model</button>

</div>

However, this method also didn't work as expected. The $watch doesn't seem to trigger when the button is pressed, and it's unclear how it would apply to my scenario. If all labels/inputs are set up this way, wouldn't all fields be highlighted when any one of them changes because hasChanged will toggle to true if any attribute of the new object differs from the old one?

I am a bit perplexed. How can I successfully implement this feature where changed fields are visually highlighted after an import operation?

Answer №1

I have previously utilized Angular.copy to duplicate the object in scope and then compared the original with the current version.

Here's an example:

Controller

$scope.initialData = angular.copy($scope.data);

View

<label for="inputLastName" 
       ng-class="initialData.lastName == data.lastName ? oldStyle:newStyle">
       Last Name:
</label>

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

sending an alert via a function's return statement

Could you explain to me why this code isn't functioning properly? When I call s.A, the alert message doesn't appear. Can you help me understand why? var s = { A: function () { alert("test A"); }, B: function () { alert("test B"); } }; ...

Extract the identifier of the class and subsequently pass it to the PHP script

How do I retrieve the id of a dynamically created class within a while loop, where the id corresponds to the user who posted it, and then send this id to PHP? Here's exactly what I'm trying to achieve: HTML: <div class='lol' id=&a ...

Triggering the open() function within an Ajax request

Upon experimenting with the method open(), I discovered that it requires a URL file as an argument. For instance, I have two functions named generateGeometricShapes() and colorShapes(). I am contemplating whether I should create separate files for each fu ...

What is the connection between {{result}} and $scope.result within AngularJS?

I comprehend the concept of binding a model to an element. An example would be... <pre ng-model="result">. This connection is established through the $scope.result variable. However, how are these two related? {{result}} $scope.result = data; ...

How to Center a DIV both Vertically and Horizontally with CSS Positioning?

I'm currently working on a webpage layout where I want to have a main div centered horizontally with three smaller divs inside, aligned both vertically and horizontally with equal spacing. I tried using margin: auto on an empty div to center it in the ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

Tips for properly aligning numbered lists in text documents

My issue involves designing an order list paragraph where I also need a paragraph in the middle of the ordered list numbers. The first paragraph is displaying correctly, but the second and third paragraphs are only appearing as single lines, so I adjuste ...

The inclusion of the <div> tag disrupts the functionality of the Material UI Grid

While attempting to enclose my element within a <div> that is nested inside the <Grid>, I realized that this was causing the <Grid> layout to break! Surprisingly, when I tried the same approach with Bootstrap grid system, this issue did n ...

Customizing CSS in apostrophe-cms Pro using TheAposPallete.vue

Just starting with apostrophe-pro and I've noticed a file named TheAposPallete.vue in the node_modules directory, located at \node_modules@apostrophecms-pro\palette\ui\apos\components This file contains the following CSS: ...

determine the proportion of the item

My function is supposed to map an object to create new keys. The new key "percent" is meant to calculate the percentage of each value of the key "data". It should be calculated as the value divided by the sum of all values. However, for some reason, it&apo ...

What is the purpose of using extends React.Component when we are designing a class component in React?

Being new to React, I find myself consumed with confusion about it day and night. As a result, my hair is falling out at an alarming rate. One thing that puzzles me is why we always need to extends React.Component when creating components with the class. ...

Encountering an error with Sequelize while using Node.js Express with PostgresQL

Apologies for the extended and ambiguous title. I am facing a challenge when attempting to add a new user to my database through an HTTP request. While I have successfully created the necessary tables using my model files, I seem to encounter difficulties ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...

Creating a combined Email and Password form field in a single row using Bootstrap

Recently, I decided to explore bootstrap. I am looking to implement email/password validation in one row on my rails app: email? | password? | OK Currently, I have a functioning code for displaying only an email field and an OK button in one row: email? ...

How to Retrieve a Scope Variable from a Controller within an Angular.js Directive

(function () { 'use strict'; angular.module('app') .controller('someController', ['$scope','localStorageService',someController]) .directive('someDirective', someDirective) function some ...

How to retrieve the parent index from within a nested forEach loop in JavaScript

var game_board = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; (function iterate() { game_board.forEach((row, i) => { row.forEach((value, j) => { // accessing indexes i and j console.log(i, j); }); }); })() I have a two-dimens ...

Manifest.json encountered an unexpected token

Recently, I deployed a react/express project on Heroku () and encountered some console errors. You can check out the errors in the Chrome console error messages. I tried researching the error, and it seems like I might need to make some changes in my mani ...

An issue has been encountered with the default selection in a dropdown menu

Struggling to make the initial option of a select box "selected" upon page load. Check out the code on Plunker In the provided plunker example, the select box appears empty when the page loads even though the deal model has a default category value. What ...

The path NPM Package is missing in the package export

For my first NPM package, I've been diving into the manuals and exploring other projects for hours to make everything work. Getting Started with the Project https://i.sstatic.net/4JIHz.png The package successfully builds, generating files for ESM an ...

Leveraging Webpack and Jest for seamless module importing in a development project

I've been working on a Node project and utilizing imports and exports extensively. To package the frontend code, I opted for Webpack. However, it seems to require running as common JS. Moreover, Jest is being used in my project, which led me to spec ...