I'm currently delving into the world of Angular and came across a puzzling issue that caught my attention. To simplify the problem, I created a concise example as the original code was considerably longer.
Desired Outcome:
I envision a scenario where a user inputs a name. If the name matches "error", it should change to red color and trigger an alert. Upon dismissing the alert by clicking 'ok', the name should revert to "initial name" and return to the color green.
Current Behavior:
Despite the intention, when the name switches to "error", the color doesn't change to red as expected.
https://i.sstatic.net/D4RYi.png
Code:
<html lang="en-US" ng-app="myApp" ng-controller="myCtrl">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div>
<input ng-model="name" ng-style="{color: myColor}"/>
</div>
</body>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $document) {
$scope.name = "initial name";
$scope.myColor = "green";
$scope.$watch('name', function() {
if($scope.name === "error") {
$scope.myColor = "red"; // Why does this line not work?
alert("Not allowed! Resetting...");
$scope.name = "initial name";
} else {
$scope.myColor = "green";
}
});
});
</script>
It's perplexing that altering $scope.myColor
doesn't lead to a color change (removing the else-clause retains the red color indefinitely). It appears that the alert
is somehow hindering the intended functionality. Even reshuffling the lines within the if-clause didn't bring any resolution.
Question:
Are there any experts who can shed light on why "error" fails to switch to red?
(I'm not necessarily seeking a fix; I'm just keen on understanding the underlying cause.)