Reputation: 1449
I am receiving data into my my $scope
as an object that contains various details of a client. I have the following models
client.name
client.email
client.programme
In my function I wish to ensure that every key has a value and nothing is left undefined.
I thought I could use ||
so go through each one and check for undefined within an if statement however this does not work.
for example:
$scope.addClient = function(newClient) {
console.log(newClient);
if(!newClient.name ||!newClient.email) {
$rootScope.$emit('errorEvent',
{"message" : "You must enter some client name"}
);
};
...performing other functions...
}
Secondly I would like to use a variable in the error message so that I can tailor it to the value that is undefined.
Upvotes: 1
Views: 68
Reputation: 1449
I ended up having to do this:
if(!client){
$rootScope.$emit('errorEvent',
{"message" : "You must enter a client name"});
}
else if(client.name === undefined) {
$rootScope.$emit('errorEvent',{"message" : "You must enter a client name" });
}
else if(client.email === undefined ) {
$rootScope.$emit('errorEvent',{"message" : "You must enter a client email" });
}
else {
REST OF FUNCTION
}
Happy to receive constructive criticism / options to reduce this code...
Upvotes: 0
Reputation: 23221
you did not attach $scope to variable.
use this
$scope.addClient = function(newClient) {
if(!newClient){
$rootScope.$emit('errorEvent',
{"message" : "You must enter some client name"});
}
else if(!$scope.newClient.name || !scope.newClient.email) {
$rootScope.$emit('errorEvent',{"message" : "You must enter some client name" });
}
}
or
$scope.addClient = function(newClient) {
if(newClient && (!$scope.newClient.name || !scope.newClient.email) || !newClient ){
$rootScope.$emit('errorEvent',
{"message" : "You must enter some client name"});
}
}
Upvotes: 1