29 Oct Building An Angular App: Part 4
Up to this point we’ve built a working application where a user can see a list of posts, add a post and also upvote that post. Although our basics are in place, it doesn’t look amazing, so let’s use bootstrap to help us out.
To start we’ll have to add the bootstrap call to our index.html file from the bootstrap CDN, we’ll also use bootstrap’s grid system to align our content, then we’ll stylize the posts list.
Our App right now isn’t holding the data, so if we were going to refresh the page we lose everything. So to start fixing this we’ll have to change our $scope.posts into a service. Inside our app.js, we’ll be adding a new service to our module.
By Angular conventions, lowerCamelCase is used for factory names that won’t be new’ed.
In angular, factory and service are related in that they are both instances of a third entity called provider.
What’s going on here is that we’re creating a new object that has an array property called posts. We then return that variable so that our o object becomes to open to any other Angular modules that want to inject it.
By exporting an object that contains the posts array we can add new objects and methods to our services in the future.
Now we have to inject the service into our controller so we can access its data.
After we injected posts into the controller we had to also inject it into the MainCtrl. What we did above was inject the posts, then in the function, we set a scope variable to mirror the array returned from the service with the posts.posts. Now any change to $scope.posts will be stored int eh service and accessible by any other module that injects posts service.
Next time we’ll start getting into routing views. Stay Tuned…
Also published on Medium.