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?