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.
There are many ways to do this.
<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
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.
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');
}
});
}
};
});
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).
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){
//
}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With