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>