I'm learning/experimenting with angular, and stumbled upon some weird behavior (in my opinion). I recreated my issue with the smallest example possible - the original code was a lot longer.
What I want this to do:
The user can enter a name. Whenever the name equals "error", its color will become red and an alert is displayed. When the alert is dismissed by the user (by clicking 'ok'), the name is reset to "initial name" and becomes green again.
What it doesn't do:
When name becomes "error", its color isn't red.
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"; // This line has no effect?
alert("Not allowed! Resetting...");
$scope.name = "initial name";
} else {
$scope.myColor = "green";
}
});
});
</script>
I know that changing $scope.myColor should change the color (if I remove the else-clause, it remains red forever), but it seems the alert is blocking the desired behavior, for some reason. I also changed the order of the lines inside the if-clause, but that didn't help.
Question:
Any geniuses out here who can explain why "error" doesn't become red?
(I don't really need a solution, I just want to know why this happens.)

modelvalue changes!$window.alertand inject$windowinto your controller. Also suggest logging the output rather that using alert if it is for debugging purposes only, using the$logservice.