0

i am trying to save a form data with angularjs into a database using php as backend. I have this html as the form

<form ng-submit="newContactSubmit()">
        <label>FirstName<input type="text" name="contact_firstname" required ng-model="newContact.contact_firstname" /></label>
        <label>LastName<input type="text" name="contact_lastname" ng-model="newContact.contact_lastname" /></label>
        <button type="submit">Save</button>
    </form>

Now the problem is lastname is not required in my case and if i send the form without filling anything in lastname, than the newContact variable has only the contact_firstname field which makes it do an error on the php side.

$scope.newContactSubmit = function() {
    alert(JSON.stringify($scope.newContact));
    /*contactService.saveContact($scope.newContact).then(function(response) {
        alert(JSON.stringify(response));
    });*/
};

The controller doesnt send the contact_lastname field as empty. Is there a way to make it define both variables even if i dont complete them ? Thank you, Daniel!

2
  • What should be the value of the empty key? null? Commented Oct 4, 2013 at 13:43
  • yes or just empty string Commented Oct 4, 2013 at 13:54

1 Answer 1

3

How about predefining default value for contact_lastname?

// inside your controller
$scope.newContact.contact_lastname = '';

so that newContact always has contact_lastname default value, even the field is left untouched.

Sign up to request clarification or add additional context in comments.

2 Comments

this could be a solution, i asked because i tought there is a mor native solution to this which i dont know :)
If you map ng-model to a variable that is not (yet) defined inside your controller, its value is undefined until user interacts with it. So you have to either define its default value or tolerate its non-existence from server-side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.