angularjs實(shí)現(xiàn)對(duì)表單輸入改變的監(jiān)控(ng-change和watch兩種方式)
angularjs通過ng-change和watch兩種方式實(shí)現(xiàn)對(duì)表單輸入改變的監(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ā)生改變時(shí),會(huì)觸發(fā)該事件<br />
<div>
姓名:<input type="text" id="name1" ng-model="user.name"
placeholder="請(qǐng)輸入姓名" ng-change="inputChange()" />
</div>
<div>
年齡:<input type="number" ng-model="user.age"
placeholder="請(qǐng)輸入年齡" ng-change="inputChange()" />
</div>
<div>{{user.message}}</div>
</div>
<div>
<h1>通過監(jiān)聽改變達(dá)到和ng-chang一樣的效果</h1>
<div>
姓名:<input type="text" id="name2" ng-model="user2.name"
placeholder="請(qǐng)輸入姓名" />
</div>
<div>
年齡:<input type="number" ng-model="user2.age"
placeholder="請(qǐng)輸入年齡" />
</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)聽實(shí)現(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實(shí)現(xiàn)對(duì)表單輸入改變的監(jiān)控,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
AngularJS使用ngOption實(shí)現(xiàn)下拉列表的實(shí)例代碼
這篇文章主要介紹了AngularJS使用ngOption實(shí)現(xiàn)下拉列表的實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-01-01
AngularJS內(nèi)建服務(wù)$location及其功能詳解
這篇文章主要為大家詳細(xì)介紹了AngularJS內(nèi)建服務(wù)$location及$location功能,感興趣的小伙伴們可以參考一下2016-07-07
簡介AngularJS中使用factory和service的方法
這篇文章主要簡單介紹了AngularJS中使用factory和service的方法,主要針對(duì)自定義工廠和服務(wù)的創(chuàng)建來講,需要的朋友可以參考下2015-06-06
angularJs中orderBy篩選以及filter過濾數(shù)據(jù)的方法
今天小編就為大家分享一篇angularJs中orderBy篩選以及filter過濾數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-09-09
Angular 1.x個(gè)人使用的經(jīng)驗(yàn)小結(jié)
這篇文章主要給大家介紹了關(guān)于Angular 1.x個(gè)人使用的一些經(jīng)驗(yàn),屬于一些基礎(chǔ)入門教程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2017-07-07

