Building A Single-Page Application With Angularjs And Wordpress Download UPDATED

Building A Single-Page Application With Angularjs And Wordpress Download

What is AngularJS?

AngularJS is a JavaScript MVC framework adult by Google that lets y'all build well structured, easily testable, and maintainable front end-finish applications.

And Why Should I Use Information technology?

If you lot haven't tried AngularJS however, you're missing out. The framework consists of a tightly integrated toolset that will help y'all build well structured, rich customer-side applications in a modular fashion—with less code and more than flexibility.

AngularJS extends HTML by providing directives that add functionality to your markup and allow y'all to create powerful dynamic templates. Yous can as well create your own directives, crafting reusable components that fill your needs and abstracting away all the DOM manipulation logic.

It likewise implements ii-way information binding, connecting your HTML (views) to your JavaScript objects (models) seamlessly. In simple terms, this means that any update on your model will exist immediately reflected in your view without the demand for any DOM manipulation or event handling (e.one thousand., with jQuery).

Angular provides services on pinnacle of XHR that dramatically simplify your code and allow you to abstruse API calls into reusable services. With that, yous can movement your model and business concern logic to the front-end and build dorsum-terminate agnostic web apps.

Finally, I dear Athwart considering of its flexibility regarding server communication. Like nigh JavaScript MVC frameworks, it lets you piece of work with any server-side technology equally long equally it can serve your app through a RESTful spider web API. Just Athwart too provides services on pinnacle of XHR that dramatically simplify your code and allow you to abstract API calls into reusable services. As a effect, yous can motion your model and business logic to the front-terminate and build dorsum-end agnostic web apps. In this post, we'll exercise but that, ane step at a time.

So, Where Do I Brainstorm?

Outset, let's make up one's mind the nature of the app nosotros want to build. In this guide, we'd prefer not to spend too much time on the back-finish, then we'll write something based on information that'due south easily accessible on the Internet—similar a sports feed app!

Since I happen to be a huge fan of motor racing and Formula 1, I'll utilise an autosport API service to act as our back-finish. Luckily, the guys at Ergast are kind plenty to provide a free motorsport API that will be perfect for us.

For a sneak peak at what we're going to build, take a look at the live demo. To prettify the demo and evidence off some Athwart templating, I applied a Bootstrap theme from WrapBootstrap, only seeing every bit this commodity isn't about CSS, I'll merely abstruse it abroad from the examples and get out it out.

Getting Started Tutorial

Let's kickstart our instance app with some average. I recommend the angular-seed project as it not only provides y'all with a great skeleton for bootstrapping, but also sets the ground for unit testing with Karma and Jasmine (we won't be doing any testing in this demo, then we'll just leave that stuff aside for at present; come across Part 2 of this tutorial for more info on setting up your project for unit of measurement and end-to-end testing).

EDIT (May 2014): Since I wrote this tutorial, the angular-seed projection has gone through some heavy changes (including the additon of Bower as package manager). If you take whatever doubts about how to deploy the project, take a quick await at the first department of their reference guide. In Part two of ths tutorial, Bower, amid other tools, is covered in greater detail.

OK, now that nosotros've cloned the repository and installed the dependencies, our app'south skeleton volition look like this:

angularjs tutorial - start with the skeleton

Now we can starting time coding. As we're trying to build a sports feed for a racing championship, allow's begin with the nigh relevant view: the championship tabular array.

the championship table

Given that nosotros already have a drivers list defined within our scope (hang with me – we'll get there), and ignoring any CSS (for readability), our HTML might look like:

          <body ng-app="F1FeederApp" ng-controller="driversController">   <tabular array>     <thead>       <tr><thursday colspan="four">Drivers Championship Standings</th></tr>     </thead>     <tbody>       <tr ng-repeat="driver in driversList">         <td>{{$index + 1}}</td>         <td>           <img src="img/flags/{{driver.Driver.nationality}}.png" />           {{commuter.Driver.givenName}}&nbsp;{{driver.Commuter.familyName}}         </td>         <td>{{driver.Constructors[0].proper noun}}</td>         <td>{{driver.points}}</td>       </tr>     </tbody>   </tabular array> </torso>                  

The first thing y'all'll discover in this template is the use of expressions ("{{" and "}}") to render variable values. In AngularJS development, expressions allow yous to execute some computation in order to return a desired value. Some valid expressions would be:

  • {{ 1 + i }}
  • {{ 946757880 | date }}
  • {{ user.name }}

Effectively, expressions are JavaScript-like snippets. Just despite being very powerful, y'all shouldn't utilize expressions to implement any higher-level logic. For that, we use directives.

Agreement Basic Directives

The second thing you lot'll notice is the presence of ng-attributes, which y'all wouldn't see in typical markup. Those are directives.

At a high level, directives are markers (such as attributes, tags, and course names) that tell AngularJS to adhere a given behaviour to a DOM element (or transform information technology, replace it, etc.). Let's take a look at the ones we've seen already:

  • The ng-app directive is responsible for bootstrapping your app defining its scope. In AngularJS, y'all tin can take multiple apps within the same page, so this directive defines where each singled-out app starts and ends.

  • The ng-controller directive defines which controller will be in charge of your view. In this case, nosotros announce the driversController, which will provide our listing of drivers (driversList).

  • The ng-repeat directive is one of the virtually normally used and serves to ascertain your template scope when looping through collections. In the example above, it replicates a line in the table for each driver in driversList.

Adding Controllers

Of class, there's no apply for our view without a controller. Let'southward add driversController to our controllers.js:

          angular.module('F1FeederApp.controllers', []). controller('driversController', function($scope) {     $scope.driversList = [       {           Commuter: {               givenName: 'Sebastian',               familyName: 'Vettel'           },           points: 322,           nationality: "German",           Constructors: [               {name: "Ruddy Bull"}           ]       },       {           Commuter: {           givenName: 'Fernando',               familyName: 'Alonso'           },           points: 207,           nationality: "Spanish",           Constructors: [               {name: "Ferrari"}           ]       }     ]; });                  

You lot may have noticed the $scope variable nosotros're passing every bit a parameter to the controller. The $scope variable is supposed to link your controller and views. In particular, information technology holds all the data that volition be used within your template. Annihilation you add to it (like the driversList in the above example) will be straight accessible in your views. For at present, let's simply work with a dummy (static) data array, which we will supercede afterwards with our API service.

Now, add this to app.js:

          angular.module('F1FeederApp', [   'F1FeederApp.controllers' ]);                  

With this line of lawmaking, we actually initialize our app and register the modules on which it depends. Nosotros'll come back to that file (app.js) after on.

Now, let'southward put everything together in alphabetize.html:

          <!DOCTYPE html> <html> <caput>   <title>F-1 Feeder</championship> </caput>  <body ng-app="F1FeederApp" ng-controller="driversController">   <table>     <thead>       <tr><th colspan="4">Drivers Title Standings</th></tr>     </thead>     <tbody>       <tr ng-echo="commuter in driversList">         <td>{{$index + ane}}</td>         <td>           <img src="img/flags/{{driver.Driver.nationality}}.png" />           {{driver.Commuter.givenName}}&nbsp;{{driver.Driver.familyName}}         </td>         <td>{{driver.Constructors[0].proper name}}</td>         <td>{{commuter.points}}</td>       </tr>     </tbody>   </table>   <script src="bower_components/angular/angular.js"></script>   <script src="bower_components/angular-route/angular-route.js"></script>   <script src="js/app.js"></script>   <script src="js/services.js"></script>   <script src="js/controllers.js"></script> </torso> </html>                  

Modulo minor mistakes, you lot tin can at present boot up your app and check your (static) list of drivers.

Note: If you need help debugging your app and visualizing your models and scope within the browser, I recommend taking a look at the awesome Batarang plugin for Chrome.

Loading Data From the Server

Since we already know how to display our controller'southward information in our view, it's fourth dimension to actually fetch live data from a RESTful server.

To facilitate communication with HTTP servers, AngularJS provides the $http and $resource services. The old is but a layer on top of XMLHttpRequest or JSONP, while the latter provides a higher level of abstraction. Nosotros'll use $http.

To abstract our server API calls from the controller, allow'south create our own custom service which will fetch our information and act as a wrapper around $http past adding this to our services.js:

          angular.module('F1FeederApp.services', []).   manufactory('ergastAPIservice', function($http) {      var ergastAPI = {};      ergastAPI.getDrivers = office() {       return $http({         method: 'JSONP',          url: 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK'       });     }      return ergastAPI;   });                  

With the first two lines, nosotros create a new module (F1FeederApp.services) and register a service within that module (ergastAPIservice). Discover that nosotros pass $http as a parameter to that service. This tells Athwart'south dependency injection engine that our new service requires (or depends on) the $http service.

In a similar fashion, nosotros need to tell Angular to include our new module into our app. Let's annals information technology with app.js, replacing our existing code with:

          angular.module('F1FeederApp', [   'F1FeederApp.controllers',   'F1FeederApp.services' ]);                  

Now, all we need to practice is tweak our controller.js a chip, include ergastAPIservice every bit a dependency, and we'll be practiced to go:

          athwart.module('F1FeederApp.controllers', []).   controller('driversController', function($telescopic, ergastAPIservice) {     $telescopic.nameFilter = null;     $scope.driversList = [];      ergastAPIservice.getDrivers().success(function (response) {         //Dig into the responde to get the relevant information         $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;     });   });                  

At present reload the app and check out the event. Notice that we didn't make any changes to our template, but we added a nameFilter variable to our scope. Let'due south put that variable to use.

Filters

Great! We have a functional controller. Only it only shows a listing of drivers. Let's add some functionality by implementing a simple text search input which volition filter our list. Let's add the following line to our index.html, right below the <trunk> tag:

          <input type="text" ng-model="nameFilter" placeholder="Search..."/>                  

We are now making employ of the ng-model directive. This directive binds our text field to the $scope.nameFilter variable and makes sure that its value is always up-to-date with the input value. At present, let's visit index.html one more time and make a small adjustment to the line that contains the ng-repeat directive:

          <tr ng-repeat="driver in driversList | filter: nameFilter">                  

This line tells ng-repeat that, before outputting the information, the driversList array must be filtered by the value stored in nameFilter.

At this betoken, two-way information bounden kicks in: every time a value is input in the search field, Angular immediately ensures that the $telescopic.nameFilter that we associated with information technology is updated with the new value. Since the binding works both means, the moment the nameFilter value is updated, the 2nd directive associated to it (i.e., the ng-repeat) also gets the new value and the view is updated immediately.

Reload the app and check out the search bar.

app search bar

Notice that this filter will look for the keyword on all attributes of the model, including the ones we´re not using. Let's say we only want to filter past Driver.givenName and Driver.familyName: Beginning, we add to driversController, right beneath the $scope.driversList = []; line:

          $telescopic.searchFilter = office (driver) {     var keyword = new RegExp($scope.nameFilter, 'i');     return !$telescopic.nameFilter || keyword.exam(driver.Driver.givenName) || keyword.test(driver.Commuter.familyName); };                  

Now, back to alphabetize.html, we update the line that contains the ng-repeat directive:

          <tr ng-repeat="driver in driversList | filter: searchFilter">                  

Reload the app ane more than time and now we have a search by name.

Routes

Our next goal is to create a commuter details page which will let usa click on each commuter and see his/her career details.

First, permit'due south include the $routeProvider service (in app.js) which will help us bargain with these varied application routes. Then, nosotros'll add together 2 such routes: one for the championship table and some other for the driver details. Hither's our new app.js:

          athwart.module('F1FeederApp', [   'F1FeederApp.services',   'F1FeederApp.controllers',   'ngRoute' ]). config(['$routeProvider', office($routeProvider) {   $routeProvider. 	when("/drivers", {templateUrl: "partials/drivers.html", controller: "driversController"}). 	when("/drivers/:id", {templateUrl: "partials/driver.html", controller: "driverController"}). 	otherwise({redirectTo: '/drivers'}); }]);                  

With that change, navigating to http://domain/#/drivers will load the driversController and look for the partial view to render in partials/drivers.html. But wait! We don't have any partial views yet, right? We'll need to create those besides.

Fractional Views

AngularJS will let you to bind your routes to specific controllers and views.

Just first, we need to tell Angular where to render these fractional views. For that, nosotros'll use the ng-view directive, modifying our alphabetize.html to mirror the following:

          <!DOCTYPE html> <html> <caput>   <title>F-i Feeder</title> </head>  <body ng-app="F1FeederApp">   <ng-view></ng-view>   <script src="bower_components/athwart/athwart.js"></script>   <script src="bower_components/angular-route/angular-route.js"></script>   <script src="js/app.js"></script>   <script src="js/services.js"></script>   <script src="js/controllers.js"></script> </trunk> </html>                  

Now, whenever we navigate through our app routes, Angular volition load the associated view and render it in identify of the <ng-view> tag. All nosotros need to exercise is create a file named partials/drivers.html and put our championship table HTML there. We'll also use this chance to link the commuter proper noun to our commuter details route:

          <input type="text" ng-model="nameFilter" placeholder="Search..."/> <table> <thead>   <tr><th colspan="iv">Drivers Title Standings</thursday></tr> </thead> <tbody>   <tr ng-repeat="commuter in driversList | filter: searchFilter">     <td>{{$alphabetize + 1}}</td>     <td>       <img src="img/flags/{{driver.Driver.nationality}}.png" />       <a href="#/drivers/{{driver.Commuter.driverId}}"> 	  	{{driver.Driver.givenName}}&nbsp;{{commuter.Driver.familyName}} 	  </a> 	</td>     <td>{{driver.Constructors[0].name}}</td>     <td>{{commuter.points}}</td>   </tr> </tbody> </tabular array>                  

Finally, allow'due south decide what nosotros want to show in the details page. How nigh a summary of all the relevant facts about the driver (e.g., birth, nationality) along with a table containing his/her contempo results? To do that, we add to services.js:

          athwart.module('F1FeederApp.services', [])   .factory('ergastAPIservice', function($http) {      var ergastAPI = {};      ergastAPI.getDrivers = role() {       render $http({         method: 'JSONP',          url: 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK'       });     }      ergastAPI.getDriverDetails = function(id) {       return $http({         method: 'JSONP',          url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/driverStandings.json?callback=JSON_CALLBACK'       });     }      ergastAPI.getDriverRaces = role(id) {       return $http({         method: 'JSONP',          url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/results.json?callback=JSON_CALLBACK'       });     }      return ergastAPI;   });                  

This time, we provide the driver's ID to the service so that nosotros retrieve the information relevant solely to a specific driver. Now, nosotros modify controllers.js:

          angular.module('F1FeederApp.controllers', []).    /* Drivers controller */   controller('driversController', role($telescopic, ergastAPIservice) {     $telescopic.nameFilter = zip;     $scope.driversList = [];     $scope.searchFilter = function (driver) {         var re = new RegExp($scope.nameFilter, 'i');         render !$scope.nameFilter || re.test(driver.Commuter.givenName) || re.examination(driver.Commuter.familyName);     };      ergastAPIservice.getDrivers().success(function (response) {         //Digging into the response to get the relevant data         $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;     });   }).    /* Driver controller */   controller('driverController', function($scope, $routeParams, ergastAPIservice) {     $telescopic.id = $routeParams.id;     $scope.races = [];     $telescopic.driver = naught;      ergastAPIservice.getDriverDetails($scope.id).success(function (response) {         $scope.commuter = response.MRData.StandingsTable.StandingsLists[0].DriverStandings[0];      });      ergastAPIservice.getDriverRaces($scope.id).success(part (response) {         $scope.races = response.MRData.RaceTable.Races;      });    });                  

The important thing to find here is that we just injected the $routeParams service into the driver controller. This service will allow united states of america to access our URL parameters (for the :id, in this case) using $routeParams.id.

Now that we take our data in the telescopic, we only need the remaining partial view. Permit's create a file named partials/driver.html and add:

          <section id="primary">   <a href="./#/drivers"><- Back to drivers list</a>   <nav id="secondary" class="main-nav">     <div class="commuter-pic">       <div class="avatar">         <img ng-show="commuter" src="img/drivers/{{driver.Commuter.driverId}}.png" />         <img ng-show="commuter" src="img/flags/{{driver.Driver.nationality}}.png" /><br/>         {{driver.Driver.givenName}} {{commuter.Driver.familyName}}       </div>     </div>     <div class="driver-status">       Country: {{driver.Commuter.nationality}}   <br/>       Team: {{driver.Constructors[0].name}}<br/>       Birth: {{driver.Driver.dateOfBirth}}<br/>       <a href="{{driver.Driver.url}}" target="_blank">Biography</a>     </div>   </nav>    <div class="primary-content">     <table grade="upshot-tabular array">       <thead>         <tr><th colspan="5">Formula 1 2013 Results</thursday></tr>       </thead>       <tbody>         <tr>           <td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td>         </tr>         <tr ng-echo="race in races">           <td>{{race.circular}}</td>           <td><img  src="img/flags/{{race.Circuit.Location.country}}.png" />{{race.raceName}}</td>           <td>{{race.Results[0].Constructor.name}}</td>           <td>{{race.Results[0].grid}}</td>           <td>{{race.Results[0].position}}</td>         </tr>       </tbody>     </table>   </div>  </section>                  

Notice that we're now putting the ng-testify directive to good use. This directive volition only show the HTML element if the expression provided is true (i.e., neither false, nor null). In this example, the avatar will only evidence up once the driver object has been loaded into the scope by the controller.

Finishing Touches

Add in a bunch of CSS and return your page. You should end upwards with something similar this:

page rendered with CSS

You're now ready to fire up your app and make sure both routes are working as desired. You lot could too add a static menu to alphabetize.html to improve the user'southward navigation capabilities. The possibilities are endless.

EDIT (May 2014): I've received many requests for a downloadable version of the code that nosotros build in this tutorial. I've therefore decided to release it here (stripped of any CSS). Nonetheless, I really practise not recommend downloading it, since this guide contains every single step yous need to build the same application with your own hands, which will exist a much more than useful and effective learning practise.

Conclusion

At this betoken in the tutorial, we've covered everything you lot'd need to write a uncomplicated app (like a Formula ane feeder). Each of the remaining pages in the alive demo (eastward.g., constructor championship tabular array, team details, agenda) share the same basic construction and concepts that we've reviewed here.

Finally, proceed in mind that Angular is a very powerful framework and we've barely scratched the surface in terms of everything it has to offering. In Part 2 of this tutorial, we'll give examples of why Athwart stands out amongst its peer front-end MVC frameworks: testability. Nosotros'll review the process of writing and running unit of measurement tests with Karma, achieving continuous integration with Yeomen, Grunt, and Bower, and other strengths of this fantastic forepart-end framework.

DOWNLOAD HERE

Posted by: walkermitcher89.blogspot.com

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel