Here's the code snippet I've been working on:
<!doctype html>
<html lang="en-US" ng-app>
<!--Head-->
<head>
<meta charset="UTF-8">
<title>Lesson 5 - ng-show & ng-hide</title>
<meta name="viewport" content="width=device-width">
<style type="text/css">
* {
box-sizing: border-box;
}
body {
font: 16px/1.5 Consolas;
color: #222;
margin: 5em;
}
</style>
</head>
<!--Body-->
<body>
<div ng-controller="information">
<!--Input-->
<label for="name">
Name:
<input type="text" name="username" id="username" placeholder="Your name here please" ng-model="name"/>
</label>
<br>
<label>
Hide?
<input type="checkbox" ng-model="checked"/>
</label>
<!--Div that is hidden-->
<div ng-hide="checked">
Hidden Message here
<br>
Welcome {{ name || "user" }}!
</div>
</div>
<script type="text/javascript" src="angular_1.0.7.js"></script>
<script type="text/javascript">
var information = function ($scope) {
$scope.$watch(function () {
console.log($scope.name);
});
};
</script>
</body>
</html>
If you run this code and update the value inside the <input>
tag, you may notice a strange behavior where the changed value is output twice in the console window every time you make a change. Here's why it happens:
The duplicated output in the console occurs due to the way the watch function is set up in the script. The $watch function listens for changes made to the scope variable bound to the input field 'name'. As a result, whenever the name value is updated, the $watch function triggers twice, causing the console log to display the updated value twice.