本文介绍了为什么要角JS事业的console.log输出不看$两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code:

<!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>

如果您来看,这并更改&LT内的值;输入&GT; 标记,然后你会看到,在控制台窗口中,每一次你改变值,将其数值变化为,输出两次,如下图所示:

If your run, this and change the value inside of the <input> tag, then you will see that in the console window, the every single time you change the value, the value you changed it to, is output twice, as shown below:

为什么会出现这种情况?

Why does this happen?

推荐答案

手表被称为每消化周期:

在$消化循环的保留迭代的,直到模型稳定,这意味着$ evalAsync队列为空,$观察名单没有检测到任何变化。

当你输入一个字符,角进入消化循环(因为角度,因为你正在使用NG-模型自动添加一个事件侦听器),并检测到变化。然后,它通过循环的再次变的,以确保没有其他变化。它这样做是因为如果$手表触发,可能会改变一些其他的观察的属性,然后需要检测,以便它可以执行监控功能。

When you type a character, Angular enters the digest loop (because Angular automatically added an event listener because you are using ng-model) and detects a change. It then goes through the loop again to ensure there are no other changes. It does this because if a $watch triggers, it might change some other watched property, which then needs to be detected so it's watch function can be executed.

这篇关于为什么要角JS事业的console.log输出不看$两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 20:29