我是 Angularjs 的初学者
<div ng-app>
<input type="text" ng-model="Number"/>
</div>
我知道可以使用 {{Number.length}} 来显示输入字段的长度, 但是如何检测长度 等..
if (length == 0) {
// do something
} else if (length == 1) {
// do something
}
如有任何建议,我们将不胜感激。
最佳答案
有很多方法可以做到这一点。
1。使用内置指令+模板
<div ng-app="app">
<input type="text" ng-model="Number"/>
<section ng-if="!Number">It's empty</section>
<section ng-if="Number">It's {{Number.length}}</section>
</div>
您也可以使用 Controller 或指令来实现相同的目的。 查看一些实际示例 -> http://jsbin.com/vaxohi/4/edit
2。使用 Controller
您可以在 Controller 中查看 Number
的值,如下所示:
app.controller('AppCtrl', function($scope){
$scope.Number = '';
$scope.$watch('Number', function(newValue){
if(newValue.length === 0){
console.log('Empty');
} else {
console.log('Has content');
}
});
});
但是,这样做并不是一个好的做法。最好的方法是使用指令。
3。使用指令
指令可以将某些行为附加到 DOM 元素;有许多内置指令(ng-if
、ng-show
等),但创建自定义指令很常见。这是一个例子:
app.directive('numberLogic', function(){
return {
restrict: 'A',
scope: {},
template: "<input type='text' ng-model='Number2'/> {{Number2}}",
link: function(scope){
scope.$watch('Number2', function(newValue){
if(newValue.length === 0){
console.log('Second number Empty');
} else {
console.log('Second number Has content');
}
});
}
};
});
顺便...
我看到你的 ng-app
指令是空的。不要忘记为您的应用传入模块名称 ng-app="appName"
并定义一个同名模块 angular.module('appName', []);
(查看 jsbin)。
关于javascript - 在angularjs中检测输入文本长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29251129/