2

I am beginner in Angularjs

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

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

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

Any advice would be highly appreciated.

2 Answers 2

19

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

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){
       console.log('Empty');
     } 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).

Sign up to request clarification or add additional context in comments.

1 Comment

link why length !=0 can't type + Can anyone Help
1

you can use ng-change

for example

<input type="text" ng-model="Number" 
ng-change="(Number.length>0)?alert('ok'):alert('no')"/>

or you can specify an function to be executed on change

<div ng-app="app">
     <div ng-controller="test">
<input type="text" ng-model="Number" 
    ng-change="checkLength()"/>
    </div>
</div>

And Js code

angular.module('app', [])
  .controller('test',function($scope){
     $scope.checkLength = function(Number){
    if(Number.length>0){
    //
    }
}
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.