This is a continuation of WordPress Application Build Part 5, so I am going to call this part 5 and a half. Or

Part 5, back with vengeance.

Where were we? Oh, ya we created the template with a basic form, but what does it all mean? We talked about ng-model in Part IV. We are going to use the object ‘newSG’ to define our new Style Guide, and this will be the object we pass into the API.

In the html for the form you will see ng-submit=”newStyleGuide()” which is the callback function for the form. A reminder, in jQuery we’d have to do a .on(‘submit’) function with e.preventDefault();. With AngularJS we do not need to do that, it is all taken care of. (Common, you know you love Angular just a little bit more now if just for not having to do e.preventDefaul() again)

What does newStyleGuide() do?

Unless mentioned, all JavaScript will be done in our controller (/assets/js/wp-app/controllers/wp-app-sg.js).

This will be the callback function defined in our controller where eventually the StyleGuides.save() will be. However for now, lets just see what it looks like when we submit data via the form.

Defining a callback function is easy, we will make it a global to the controller by defining it within the $scope object. Go ahead and load it up, remember our URL route – http://localDomain/#/new-style-guide

There shouldn’t be any errors, what you should get in the console is an object like this one:

There is an issue with that though, we need more data just to get it going properly. First, by default when a new post is created it is put into “draft” status, so that the API won’t return it when we do a GET request. There are filters to get drafts, but for now lets just assume we want the form to auto publish a new post.

Defining additional data without hidden inputs

We are defining the object and passing in ‘status’ and ‘post_type’. Let us run the form again and see if the new data is returned in object we see in the console.

Saving a new post

Finally, we have reached the end. Now we have to actually push the data to the API

I console log the response here because I know the API responds with the full post data, if the ID exists then it was successful. You can verify by going into your WP admin and looking at the Style Guides to see if a new one is created (which it should be).

If you have any issues with this functionality contact me and I will help you out.

That is it for now, next time we will focus more on creating the custom meta data for the post.

There is one comment

Comments are closed.