键入时角度更改文本颜色

时间:2016-03-11 19:02:54

标签: angularjs

我有以下内容:

<input type="number" ng-model="myNumber">

$scope.$watch('myNumber', function(nV, oV) {
 $scope.myNumberPlus10 = (nV + 10);  
});

<span>{{ myNumberPlus10 }}</span>

我想将<span>{{ myNumberPlus10 }}</span>文字颜色更改为绿色,因为我在<input>中输入了一个数字,但是一旦我完成了打字,我就会喜欢要恢复原始文本颜色的颜色。

3 个答案:

答案 0 :(得分:0)

您可以在输入中使用ng-focus和ng-blur指令,并在跨度上使用ng-style; ng-focus和ng-blur可以将变量设置为true或false,具体取决于输入字段是否处于焦点,而span的ng-style将观察该变量并确定是否将字体变为绿色。

<input type="number" ng-model="myNumber" ng-focus="focus=true" ng-blur="focus=false">

$scope.$watch('myNumber', function(nV, oV) {
 $scope.myNumberPlus10 = (nV + 10);  
});

<span ng-style="{focus: 'color:green'}">{{ myNumberPlus10 }}</span>

或带有一些css类的ng-class将颜色设置为绿色(下例中的“绿色文本”):

<span ng-class="{'green-text':focus}">{{ myNumberPlus10 }}</span>

答案 1 :(得分:0)

只需使用:focus CSS选择器,这与Angular无关,无需过度复杂化:

angular.module('app', [])
  .controller('Ctrl', function($scope) {
    $scope.myNumber = 0;
    $scope.$watch('myNumber', function(nV, oV) {
      $scope.myNumberPlus10 = (nV + 10);
    })
  })
input:focus + span {color: green}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
  <input type="number" ng-model="myNumber" />
  <span>{{myNumberPlus10}}</span>
</div>

答案 2 :(得分:0)

angular.module('myApp', [])
	.controller('ctrl', function ($scope, $timeout){
  	var timeout;
    $scope.myNumber = null;
    $scope.myNumberPlus10 = null;
    $scope.style = {color: 'red'};
    
    $scope.keyPressed = function () {
    	var myNumber = parseInt($scope.myNumber,10);
      if (timeout) {
       	$timeout.cancel(timeout);
      }
      timeout = $timeout(function (){
      	$scope.style = {color: 'red'};
      }, 1000); 
      $scope.style = {color: 'green'};
      $scope.myNumberPlus10 = isNaN(myNumber) ? null : myNumber + 10;
    }
    
    
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<div>
<input type="text" ng-model="myNumber" ng-keyup="keyPressed()">
<span ng-style="style">{{myNumberPlus10}}</span>
</div>
</div>