AngularJS Tutorial
April 5, 2017 | Author: Zoth Bernstein | Category: N/A
Short Description
Download AngularJS Tutorial...
Description
You are now ready to build the AngularJS phonecat app. In this step, you will become familiar with the most important source code files, learn how to start the development servers bundled with angular-seed, and run the application in the browser. • •
Git on Mac/Linux Git on Windows 1. In angular-phonecat directory, run this command: 1. git checkout -f step-0
This resets your workspace to step 0 of the tutorial app. You must repeat this for every future step in the tutorial and change the number to the number of the step you are on. This will cause any changes you made within your working directory to be lost. 2. To see the app running in a browser, do one of the following: • For node.js users: 1. In a separate terminal tab or window, run ./scripts/web-server.js to start the web server. 2. Open a browser window for the app and navigate to http://localhost:8000/app/index.html • For other http servers: 1. Configure the server to serve the files in the angular-phonecat directory. 2. Navigate in your browser to http://localhost:[port-number]/[contextpath]/app/index.html. You can now see the page in your browser. It's not very exciting, but that's OK. The HTML page that displays "Nothing here yet!" was constructed with the HTML code shown below. The code contains some key Angular elements that we will need going forward. app/index.html: 1. 2. 3. 4.
5.
My HTML File
6.
7.
8.
9. 10. 11. 12.
Nothing here {{'yet' + '!'}}
13. 14. 15.
What is the code doing? •
ng-app directive: The ng-app attribute represents an Angular directive (named ngApp; Angular uses namewith-dashes for attribute names and camelCase for the corresponding directive name) used to flag an element which Angular should consider to be the root element of our application. This gives application developers the freedom to tell Angular if the entire html page or only a portion of it should be treated as the Angular application.
•
AngularJS script tag: This code downloads the angular.js script and registers a callback that will be executed by the browser when the containing HTML page is fully downloaded. When the callback is executed, Angular looks for the ngAppdirective. If Angular finds the directive, it will bootstrap the application with the root of the application DOM being the element on which the ngApp directive was defined.
•
Double-curly binding with an expression: Nothing here {{'yet' + '!'}} This line demonstrates the core feature of Angular's templating capabilities – a binding, denoted by double-curlies{{ }} as well as a simple expression 'yet' + '!' used in this binding. The binding tells Angular that it should evaluate an expression and insert the result into the DOM in place of the binding. Rather than a one-time insert, as we'll see in the next steps, a binding will result in efficient continuous updates whenever the result of the expression evaluation changes. Angular expression is a JavaScript-like code snippet that is evaluated by Angular in the context of the current model scope, rather than within the scope of the global context (window). As expected, once this template is processed by Angular, the html page contains the text: "Nothing here yet!".
Bootstrapping AngularJS apps Bootstrapping AngularJS apps automatically using the ngApp directive is very easy and suitable for most cases. In advanced cases, such as when using script loaders, you can use imperative / manual way to bootstrap the app. There are 3 important things that happen during the app bootstrap:
1. The injector that will be used for dependency injection within this app is created. 2. The injector will then create the root scope that will become the context for the model of our application. 3. Angular will then "compile" the DOM starting at the ngApp root element, processing any directives and bindings found along the way. Once an application is bootstrapped, it will then wait for incoming browser events (such as mouse click, key press or incoming HTTP response) that might change the model. Once such an event occurs, Angular detects if it caused any model changes and if changes are found, Angular will reflect them in the view by updating all of the affected bindings. The structure of our application is currently very simple. The template contains just one directive and one static binding, and our model is empty. That will soon change!
What are all these files in my working directory? Most of the files in your working directory come from the angular-seed project which is typically used to bootstrap new Angular projects. The seed project includes the latest Angular libraries, test libraries, scripts and a simple example app, all pre-configured for developing a typical web app. For the purposes of this tutorial, we modified the angular-seed with the following changes: • • •
Removed the example app Added phone images to app/img/phones/ Added phone data files (JSON) to app/phones/
Added Bootstrap files to app/css/ and app/img/
•
Experiments Try adding a new expression to the index.html that will do some math:
•
1 + 2 = {{ 1 + 2 }}
Summary Now let's go to step 1 and add some content to the web app.
In order to illustrate how Angular enhances standard HTML, you will create a purely static HTML page and then examine how we can turn this HTML code into a template that Angular will use to dynamically display the same result with any set of data. In this step you will add some basic information about two cell phones to an HTML page. Workspace Reset Instructions ➤ The page now contains a list with information about two phones. The most important changes are listed below. You can see the full diff on GitHub: app/index.html: 1. 2.
3.
Nexus S
4.
5.
Fast just got faster with Nexus S.
6.
7.
8.
9.
Motorola XOOM™ with Wi-Fi
10.
11. 12. 13.
The Next, Next Generation tablet.
14.
Experiments •
Try adding more static HTML to index.html. For example: Total number of phones: 2
Summary
This addition to your app uses static HTML to display the list. Now, let's go to step 2 to learn how to use AngularJS to dynamically generate the same list.
Now it's time to make the web page dynamic — with AngularJS. We'll also add a test that verifies the code for the controller we are going to add. There are many ways to structure the code for an application. For Angular apps, we encourage the use of the Model-View-Controller (MVC) design pattern to decouple the code and to separate concerns. With that in mind, let's use a little Angular and JavaScript to add model, view, and controller components to our app. Workspace Reset Instructions ➤ The app now contains a list with three phones. The most important changes are listed below. You can see the full diff on GitHub:
View and Template In Angular, the view is a projection of the model through the HTML template. This means that whenever the model changes, Angular refreshes the appropriate binding points, which updates the view. The view component is constructed by Angular from this template: app/index.html: 1. 2. 3.
...
4.
5.
6. 7. 8. 9.
10. 11. 12. 13. 14.
{{phone.name}} {{phone.snippet}}
15. 16.
We replaced the hard-coded phone list with the ngRepeat directive and two Angular expressions enclosed in curly braces: {{phone.name}} and {{phone.snippet}}: •
The ng-repeat="phone in phones" statement in the tag is an Angular repeater. The repeater tells Angular to create a element for each phone in the list using the first tag as the template.
As we've learned in step 0, the curly braces around phone.name and phone.snippet denote bindings. As opposed to evaluating constants, these expressions are referring to our application model, which was set up in ourPhoneListCtrl controller.
•
Model and Controller The data model (a simple array of phones in object literal notation) is instantiated within the PhoneListCtrlcontroller: app/js/controllers.js: 1. function PhoneListCtrl($scope) { 2. 3. 4. 5. 6.
$scope.phones = [ {"name": "Nexus S", "snippet": "Fast just got faster with Nexus S."}, {"name": "Motorola XOOM™ with Wi-Fi", "snippet": "The Next, Next Generation tablet."},
7.
{"name": "MOTOROLA XOOM™",
8.
"snippet": "The Next, Next Generation tablet."}
9.
];
10. }
Although the controller is not yet doing very much controlling, it is playing a crucial role. By providing context for our data model, the controller allows us to establish data-binding between the model and the view. We connected the dots between the presentation, data, and logic components as follows: •
PhoneListCtrl — the name of our controller function (located in the JavaScript file controllers.js), matches the value of the ngController directive located on the tag.
•
The phone data is then attached to the scope ($scope) that was injected into our controller function. The controller scope is a prototypical descendant of the root scope that was created when the application bootstrapped. This controller scope is available to all bindings located within the tag. The concept of a scope in Angular is crucial; a scope can be seen as the glue which allows the template, model and controller to work together. Angular uses scopes, along with the information contained in the template, data model, and controller, to keep models and views separate, but in sync. Any changes made to the model are reflected in the view; any changes that occur in the view are reflected in the model. To learn more about Angular scopes, see the angular scope documentation.
Tests The "Angular way" makes it easy to test code as it is being developed. Take a look at the following unit test for your newly created controller: test/unit/controllersSpec.js: 1. describe('PhoneCat controllers', function() { 2. 3.
describe('PhoneListCtrl', function(){
4. 5.
it('should create "phones" model with 3 phones', function() {
6.
var scope = {},
7.
ctrl = new PhoneListCtrl(scope);
8. 9.
expect(scope.phones.length).toBe(3);
10. 11.
}); });
12. });
The test verifies that we have three records in the phones array and the example demonstrates how easy it is to create a unit test for code in Angular. Since testing is such a critical part of
software development, we make it easy to create tests in Angular so that developers are encouraged to write them. Angular developers prefer the syntax of Jasmine's Behavior-driven Development (BDD) framework when writing tests. Although Angular does not require you to use Jasmine, we wrote all of the tests in this tutorial in Jasmine. You can learn about Jasmine on the Jasmine home page and on the Jasmine wiki. The angular-seed project is pre-configured to run all unit tests using Testacular. To run the test, do the following: 1. In a separate terminal window or tab, go to the angular-phonecat directory and run ./scripts/test.sh to start the Testacular server. 2. Testacular will start a new instance of Chrome browser automatically. Just ignore it and let it run in the background. Testacular will use this browser for test execution. 3. You should see the following or similar output in the terminal: info: Testacular server started at http://localhost:9876/ info (launcher): Starting browser "Chrome" info (Chrome 22.0): Connected on socket id tPUm9DXcLHtZTKbAEO-n Chrome 22.0: Execu ted 1 of 1 SUCCESS (0.093 secs / 0.004 secs) Yay! The test passed! Or not... 4. To rerun the tests, just change any of the source or test files. Testacular will notice the change and will rerun the tests for you. Now isn't that sweet?
Experiments •
Add another binding to index.html. For example: Total number of phones: {{phones.length}}
•
Create a new model property in the controller and bind to it from the template. For example: $scope.hello = "Hello, World!" Refresh your browser to make sure it says, "Hello, World!"
•
Create a repeater that constructs a simple table: row number 0, 1, 2, 3, 4, 5, 6, 7]">{{i}}
View more...
Comments