Reputation: 2015
I'm fairly new to Angular. Here is a controller I'm working on...
svs.controller('registrationCtrl', function($scope, validatorService) {
$scope.$watch("registrationForm.email.value", function(newValue, oldValue) {
if (validatorService.validateEmail(newValue)) {
$scope.registrationForm.email.valid = true;
} else {
$scope.registrationForm.email.valid = false;
}
});
});
On the associated view, there is a text input for the user's email. It's set to have Angular use $scope.registrationForm.email.value
as the model. This seems to be the case, as if I remove everything from inside the $watch
function, and just do a simple console log, it logs whenever I change the value of the text input.
The idea here is to have an object at $scope.registrationForm
that looks similar to this...
{
email: {
value: "[email protected]",
valid: true
}
}
I'm attempting to watch the value of the text area, use a service method to validate the email, and setting the valid
property of registrationForm.email
to true
when it is valid.
Unfortunately, I'm getting an error...
TypeError: Cannot read property 'email' of undefined
I have not explicitly defined in the JavaScript registrationForm.email.valid
, nor have I made any reference to it in the HTML of my view.
Do I need to create this property before setting it? What is going on here?
Upvotes: 0
Views: 85
Reputation: 11973
yes you have to create a property before setting.
$scope.email={};
Upvotes: 1
Reputation: 424
You don't have to do it like this, because... angular already makes it. Everything you need is adding attribute name to form and to input.
<script>
angular.module('emailExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.email = {
text: '[email protected]'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Email:
<input type="email" name="input" ng-model="email.text" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
</div>
<tt>text = {{email.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
More details available here
Upvotes: 1