AngularJS算是一個的框架,所以HTML屬於view,那麼model就是ng-model等標籤,接著便需要controller來加以綁定,在此javascript則扮演controller的角色,以下範例利用controller來進行"輸入錯誤"的檢測,若使用者輸入非正整數數字則會顯是錯誤訊息,此外利用ng-class來做顏色識別,錯誤為紅、正確為綠。
數量:
價格:
價格:
{{sum}}
一、首先一樣設計出輸入視窗,只是將之前的範例稍微做了修改。
(一)為了進行顏色識別,先設計兩個CSS樣式分別為紅色、綠色。<style type="text/css">
.Red{
color:red;
}
.Green{
color:green;
}
</style>
(二)增加<div>標籤加入了ng-controller並設定變數為control<div ng-controller="control">(三)在h1中加入ng-class並設定屬性值如下,代表isActive為true執行紅色反之則綠色:
<h1 ng-class="{true:'Red',false:'Green'}[isActive]" ng-model="sum">
{{sum}}</h1>
(四)controller透過javascript進行業務邏輯運算,$scope是重要的參數它是屬於整個control的管轄範圍變數,另外利用$scope.$watch來進行事件的監聽,以做後續處理,處理核心在於check函數。<script language="javascript">
var control = function($scope){
$scope.quantity = -1;
$scope.price = 500;
$scope.$watch('quantity', function(){
check($scope);
});
$scope.$watch('price', function(){
check($scope);
});
};
function check($scope){
var quantity = parseInt($scope.quantity);
var price = parseInt($scope.price);
var sum = parseInt(quantity * price);
if (isNaN(sum) || sum < 0) {
$scope.sum = "請輸入正整數";
$scope.isActive = true;
}
else {
$scope.sum = sum;
$scope.isActive = false;
}
}
</script>
二、完整程式碼:http://jsbin.com/xedey/1/edit
<!DOCTYPE html>
<html ng-app>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style type="text/css">
.Red{
color:red;
}
.Green{
color:green;
}
</style>
<script language="javascript">
var control = function($scope){
$scope.quantity = -1;
$scope.price = 500;
$scope.$watch('quantity', function(){
check($scope);
});
$scope.$watch('price', function(){
check($scope);
});
};
function check($scope){
var quantity = parseInt($scope.quantity);
var price = parseInt($scope.price);
var sum = parseInt(quantity * price);
if (isNaN(sum) || sum < 0) {
$scope.sum = "請輸入正整數";
$scope.isActive = true;
}
else {
$scope.sum = sum;
$scope.isActive = false;
}
}
</script>
</head>
<body>
<div ng-controller="control">
數量:
<input ng-model="quantity" placeholder="Enter price here" type="number" />
<br />
價格:
<input ng-model="price" placeholder="Enter quantity here" type="number" />
<br />
<hr />
<h1 ng-class="{true:'Red',false:'Green'}[isActive]" ng-model="sum">
{{sum}}</h1>
</div>
</body>
</html>
留言
張貼留言