Encountered a similar issue while attempting to enhance text highlighting during a data bind process. The objective is to emphasize the modified text for a more polished user interface. This approach ensures that users are aware of any changes as they complete a form.
Key Learnings (Referenced fiddle here)
Firstly, avoiding the use of watch is crucial, as it can create undesirable true::false cycles within ng-class, resulting in a messy transition.
Secondly, Angular should not be approached like jQuery where elements are located and altered; reusability is central which my initial attempts lacked.
Thirdly, events such as ng-focus, ng-blur, ng-click, among others, play a vital role in achieving the desired outcomes.
The solution involves using ng-focus and ng-blur to track edits made to an input field:
<input ng-focus="highlight('name')" ng-blur="doneHighlight('name')"
ng-model="user.name" />
Calling the highlight function during ng-focus passes an argument ('name') critical for reusability.
$scope.highlight = function(className){
$scope.toggle = className;
}
Once passed through, toggle takes on the value of the argument.
Now, here's the trick...
<div ng-class="{'toggle': toggle=='name', 'noToggle': toggle=='name'+false}">
{{user.name}}
</div>
When toggle matches the passed argument, the highlight is applied, while when it equals 'name' + false, the 'noToggle' class triggers a smooth unhighlight animation.
But what about ng-blur? Well, ng-blur calls the 'doneHighlight' function with the same class argument.
$scope.doneHighlight = function(className){
$scope.toggle = className + false;
}
Here, the argument includes a false value, indicating a different approach from jQuery but allowing for controller function reuse across multiple elements.
Hoping this explanation proves helpful! Feel free to ask any further questions.
Access the fiddle here.