AnhNg AnhNg - 6 months ago 12
AngularJS Question

Angular scope doesn't update even with apply()

I have a problem with Angular's scope:

Init Angular:

<html lang="en" ng-app="ant101App" ng-controller="regFormController as reg">


Script:

script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('ant101App',[]);
app.controller('regFormController', function() {
this.message = null;
if ((''+this.fname).length > 15) {
this.message = 'First name should be less than 16 characters!';
}
});
</script>


HTML:

<p>{{reg.message}}</p>

<input ng-model="reg.fname" type="text" name="firstname" class="afirst-name-box" placeholder="First name" required>


When I enter first name, reg.message doesnt update.
When I use aplly(), it even caused error, and just displayed {{reg.message}} in html page

<script>
var app = angular.module('ant101App',[]);
app.controller('regFormController', function() {
this.message = null;
this.$apply(function(){
if ((''+this.fname).length > 15) {
this.message = 'First name should be less than 16 characters!';
}
});
});
</script>


So how can I update reg.message when reg.fname changed?

Answer

Basically you want to validate the input on keyPress.

You should be doing this.

<input ng-model="reg.fname" type="text" name="firstname" class="afirst-name-box" placeholder="First name" required ng-keypress="reg.validateName()">

and in controller

app.controller('regFormController', function() {
        this.message = null;
        this.validateName = function() {
           if ((''+this.fname).length > 15) {
                this.message = 'First name should be less than 16 characters!';
           }
        };       
    });
Comments