angularjs實現(xiàn)對表單輸入改變的監(jiān)控(ng-change和watch兩種方式)
更新時間:2018年08月29日 14:13:26 作者:返回主頁 xiaoxuzi
這篇文章主要介紹了angularjs通過ng-change和watch兩種方式實現(xiàn)對表單輸入改變的監(jiān)控,需要的朋友可以參考下
angularjs通過ng-change和watch兩種方式實現(xiàn)對表單輸入改變的監(jiān)控
直接上練習(xí)代碼
<!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指令,當(dāng)表單輸入發(fā)生改變時,會觸發(fā)該事件<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>通過監(jiān)聽改變達到和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監(jiān)聽實現(xiàn)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>
總結(jié)
以上所述是小編給大家介紹的angularjs實現(xiàn)對表單輸入改變的監(jiān)控,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
詳解Angular 4.x NgTemplateOutlet
這篇文章主要介紹了詳解Angular 4.x NgTemplateOutlet,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
用AngularJS來實現(xiàn)監(jiān)察表單按鈕的禁用效果
本篇文章主要介紹了用AngularJS來實現(xiàn)監(jiān)察表單按鈕的禁用效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2016-11-11
Angular中AuthGuard路由守衛(wèi)的創(chuàng)建使用
這篇文章主要為大家介紹了Angular中AuthGuard路由守衛(wèi)的創(chuàng)建使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
2023-07-07
AngularJS 實現(xiàn)JavaScript 動畫效果詳解
本文主要介紹AngularJS 實現(xiàn) JavaScript 動畫的資料,這里整理了詳細的資料和簡單示例代碼,有興趣的小伙伴可以參考下
2016-09-09 
