Adding New Posts

You’ve now linked up the code to Angular such that your controller is providing the data and then allowing the view to display it, but right now it’s the same as when you started with the static HTML.

What you need to do is have a field on the page for users to add new posts.

If you add a new element to the $scope.posts array, Angular will automatically update the view to show it. If you also have an input and button on the page to add a new post, you just need to append to that array.

To illustrate, let’s add a button to the page. Before the list-group <ul>, add this button:

<button ng-click='addPost()' class='btn btn-default'>Add Post</button>

ng-click is a directive that is typically used to call a function on $scope. Right now clicking it will do nothing, but if you add the function, you can add a new post to your list of posts. Add the following line inside your controller:

$scope.addPost = function () {
  $scope.posts.unshift({
    username: 'dickeyxxx',
    body: 'my new post!'
  })
}

unshift is a JavaScript method on arrays that pushes a new element to the beginning of the array. You should now be able to click the Add Post button and add elements to the list

Image

Angularized Recent Posts page

Because you didn’t have to write any code to actually update the list when $scope.posts changed, this allows you to cleanly separate the logic that updates the data from the view logic. If you updated the posts by deletion, Ajax call, or WebSockets information, you just need to update $scope.posts, and Angular will take care of updating the view for you.

Now you need to add a couple of inputs to let the user put their own body in as the post. To do this, you will add an <input> to the page, data bind it to $scope, and then use that under addPost(). Add the following HTML before the Add Post button:

<input ng-model='postBody' class='form-control' />

The ng-model directive hooks an input to a $scope property. Now if you access $scope.postBody inside the controller, you’ll get the data inside this text field.

To use this instead of your stock data, update the addPost() function like so:

$scope.addPost = function () {
  $scope.posts.unshift({
    username: 'dickeyxxx',
    body: $scope.postBody
  })
}

Now whatever the user enters in the input field will be their post body.