angularjs通过ng-change和watch两种方式实现对表单输入改变的监控

angularjs通过ng-change和watch两种方式实现对表单输入改变的监控

直接上练习代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body ng-app="myApp" ng-controller="myContro">
    <div>
        <h1>ng-change指令</h1>
        ng-change指令,当表单输入发生改变时,会触发该事件<br />
        <div>
            姓名:<input type="text" id="name1" ng-model="user.name"
                placeholder="请输入姓名" ng-change="inputChange()" />
        </div>
        <div>
            年龄:<input type="number" ng-model="user.age"
                placeholder="请输入年龄" ng-change="inputChange()" />
        </div>
        <div>{{user.message}}</div>
    </div>
    <div>
        <h1>通过监听改变达到和ng-chang一样的效果</h1>
        <div>
            姓名:<input type="text" id="name2" ng-model="user2.name"
                placeholder="请输入姓名" />
        </div>
        <div>
            年龄:<input type="number" ng-model="user2.age"
                placeholder="请输入年龄" />
        </div>
        <div>{{user2.message}}</div>
    </div>
</body>
</html>
<script src="../JS/angular.js"></script>
<script type="text/javascript">
    var app = angular.module("myApp", []);
    app.controller("myContro", function ($scope, $interpolate) {
        $scope.user = {
            name: "",
            age: "",
            message: ""
        };

        $scope.user2 = {
            name: "",
            age: "",
            message: ""
        };

        $scope.messageTemp = "{{name}},您好,您今年{{age}}岁啦!";
        var template = $interpolate($scope.messageTemp);
        $scope.inputChange = function () {
            $scope.user.message = template({ name: $scope.user.name, age: $scope.user.age });
        };

        //// 下面通过watch监听实现ng-change一样的效果
        $scope.$watch("user2.name", function (newValue, oldValue) {
            $scope.getMessage(newValue, oldValue);
        });

        $scope.$watch("user2.age", function (newValue, oldValue) {
            $scope.getMessage(newValue, oldValue);
        });

        $scope.getMessage = function (value1, value2) {
            if (value1 != value2) {
                $scope.user2.message = template({ name: $scope.user2.name, age: $scope.user2.age });
            }
        }
    });
</script>

 

END

上面整理了一些在实际业务开发中遇到的关于页面加载慢的排查和解决的方法。后面还会越来月丰富起来,如果你的项目有可能遇到打开慢的情况,不妨点赞收藏一下~。

END
为了更高的交流,欢迎大家关注我的公众号,扫描下面二维码即可关注,谢谢:

posted @ 2018-08-29 12:18  程序员修炼之旅  阅读(2202)  评论(0编辑  收藏  举报
END
欢迎各位小伙伴关注我的公众号(程序员修炼之旅),里面会分享一些技术类干货,同时也是一个技术沟通交流平台,谢谢大家的支持。