Allenph Allenph - 3 months ago 8
AngularJS Question

Why is an object utilized by Angular undefined?

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: "someEmail@emailProvider.com",
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?

Answer

yes you have to create a property before setting.

$scope.email={};
Comments