欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-14 10:33:19
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>

总结

以上所述是小编给大家介绍的angularjs实现对表单输入改变的监控,希望对大家有所帮助