我对Angular的范围有疑问:
Init Angular:
<html lang="en" ng-app="ant101App" ng-controller="regFormController as reg">
脚本:
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>
当我输入名字时,reg.message不会更新。 当我使用aplly()时,它甚至导致错误,并在html页面中显示{{reg.message}}
<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>
那么当reg.fname改变后如何更新reg.message?
答案 0 :(得分:0)
基本上你想验证keyPress上的输入。
你应该这样做。
<input ng-model="reg.fname" type="text" name="firstname" class="afirst-name-box" placeholder="First name" required ng-keypress="reg.validateName()">
并在控制器中
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!';
}
};
});
答案 1 :(得分:0)
您可以使用 ng-change 指令运行更新功能。 Plunker中的工作示例:https://plnkr.co/edit/KH6bhumLjz7VR1dmE16r?p=preview
在控制器中:
this.updateName = function() {
if ((''+this.fname).length > 15) {
this.message = 'First name should be less than 16 characters!';
}
HTML:
<input ng-change="reg.updateName()" type="text" required="" placeholder="First name" class="afirst-name-box" name="firstname" ng-model="reg.fname" />