歚木省

如何实现input输入时和值为空时的状态变化

下面以一段代码进行演示,其中涉及的知识点为angular的element元素(angular中jqLite的写法)和angular中的$watch事件。

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" /> 

<title>$apply()、$timeout()、$watch()</title>

<script type="text/javascript" src="js/jquery-1.12.3.js"></script>

<script src="angular/angular.min.js"></script>

</head>

<body>

<div ng-app="myApp">

<div ng-controller="myController">

<div>

单价:{{order.price}}

</div> 

<input type="text" ng-model="money" ng-change='go()' id='in'/>


</div>

<div>

数量: <select ng-model="order.num" ng-options="item for item in numOptions"></select>

</div> 

<div>

总价:{{sum()}}

</div> 

<div>

运费:{{order.ship}}

</div> 

<div>

<button ng-click="submit()">Submit</button>

</div>

</div>

</div> 

<script type="text/javascript">

var app = angular.module('myApp', []); 

app.controller('myController', function ($scope) {

$scope.go=function(){

angular.element('#in').css('backgroundColor','green');

angular.element('#in').css('color','yellow');

$scope.$watch($scope.money,function(newVal,oldVal){

if(newVal==null){

angular.element('#in').css('backgroundColor','white');

}

})

}

$scope.numOptions = [1, 2, 3]; 

$scope.order = {

price:50, 

num:3

}; 

$scope.sum = function(){

return $scope.order.price * $scope.order.num;

};

// 用户点击“Submit” button 后执行的方法

$scope.submit = function(){

console.log($scope.ship);

};

// 监听 $scope.sum 的改变

$scope.$watch($scope.sum, function(newVal, oldVal){

// newVal 是 $scope.sum() 最新计算出来的值,oldVal 是 上一次计算出来的值

$scope.ship = newVal > 100 ? 0 : 10;

});

});

</script>

</body>

</html>


评论

© 歚木省 | Powered by LOFTER