首页 > 代码库 > AngularJS 中ng-model通过$watch动态取值

AngularJS 中ng-model通过$watch动态取值

这个例子的意思是,当xxxx的长度不超过6时,xxxx和yyyy两个input的model是无关的,但当xxxx超过6,则yyyy会跟随其值而变化。

 

<!doctype HTML>
<html>

<head lang="en">
  <meta charset="utf-8">

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <script type="text/javascript">
    var app = angular.module(‘app‘, []);
    app.controller(‘AppCtrl‘, function($scope) {

      $scope.xxxx = "apple";
      $scope.yyyy = "banana";

      $scope.$watch(‘xxxx‘, function() {

        if ($scope.xxxx.length > 6) {
          $scope.yyyy = "***" + $scope.xxxx + "***";
        } else {}
      });
    });
  </script>


</head>

<body ng-app="app" ng-controller="AppCtrl">

  <input type="text" ng-model="xxxx">
  <input type="text" ng-model="yyyy">

  <br/>
  <p>{{xxxx}}</p>
  <p>{{yyyy}}</p>

</body>

</html>

  

AngularJS 中ng-model通过$watch动态取值