2016-05-15 67 views
0

我無法看到ng-maxlength達到的字符數。即使超過ng-maxlength,如何顯示文本長度?

var app = angular.module('plunker', []); 
 
app.controller('MainCtrl', function($scope) { 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="plunker" ng-controller="MainCtrl"> 
 
    <form name="form" novalidate> 
 
    <input type="text" ng-model="myChar" ng-maxlength="5"> 
 
    <br> 
 
    <h1>Length: {{myChar.length}}</h1> 
 
    </form> 
 
</div>

回答

0

那是因爲你已經超過了後maxlengthmyChar$modelValue是不確定的。您仍然可以使用$viewValue屬性,如下例所示。

var app = angular.module('plunker', []); 
 
app.controller('MainCtrl', function($scope) { 
 
    $scope.test = function() { 
 
    console.log($scope.form.myChar.$viewValue.length); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> 
 
<div ng-app="plunker" ng-controller="MainCtrl"> 
 
    <form name="form" novalidate> 
 
    <input type="text" name="myChar" ng-model="myChar" ng-maxlength="5" ng-keyup="test()"> 
 
    <br> 
 
    <h1>Length: {{myChar.length}}</h1> 
 
    </form> 
 
</div>

0

只是提高了@約翰·史密斯的回答是:

你可以直接把他驗證你的HTML表達。然後,你可以用一些CSS樣式它顯示了長度無效的用戶:

var app = angular.module('plunker', []); 
 
app.controller('MainCtrl', function($scope) { 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> 
 
<style> 
 
.red { 
 
color: red; 
 
} 
 
</style> 
 
<div ng-app="plunker" ng-controller="MainCtrl"> 
 
    <form name="form" novalidate> 
 
    <input type="text" name="myChar" ng-model="myChar" ng-maxlength="5"> 
 
    <br> 
 
    <h1 ng-class="{'red': form.myChar.$viewValue.length > 5}">Length: {{form.myChar.$viewValue.length}}</h1> 
 
    </form> 
 
</div>

相關問題