1. 程式人生 > >AngularJS 中ng-model通過$watch動態取值

AngularJS 中ng-model通過$watch動態取值

blog html lib brush google java logs con head

這個例子的意思是,當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動態取值