Duke Duke - 9 months ago 45
Javascript Question

Detect Input text length in angularjs

I am beginner in Angularjs

<div ng-app>
<input type="text" ng-model="Number"/>

I know can use {{Number.length}} to display input field length,
But how detect length

if (length == 0) {
do something
} else if (length == 1) {
do something}

Any advice would be highly appreciated.

Answer Source

There are many ways to do this.

1. Using built-in directives + template

<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>

You could also use a controller or directive to achieve the same thing. See some examples in action -> http://jsbin.com/vaxohi/4/edit

2. Using a controller

You can watch the value of Number in a controller, like so:

app.controller('AppCtrl', function($scope){
  $scope.Number = '';
  $scope.$watch('Number', function(newValue){
     if(newValue.length === 0){
     } else {
       console.log('Has content');

However, it's not a good practice to do it like this. The best way to do it is by using a directive.

3. Using a directive

Diretives can attach certain behavior to DOM elements; there are many built-in directives (ng-if, ng-show, etc), but it's very common to create custom ones. Here's an example:

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');

By the way...

I see your ng-app directive is empty. Don't forget to pass in a module name for your app ng-app="appName" and define a module with the same name angular.module('appName', []); (See the jsbin).