- https://www.codecademy.com/courses/learn-angularjs/lessons/your-first-app/exercises/your-first-app-workflow?action=lesson_resume
- In app.js, we created a new module named
myApp. A module contains the different components of an AngularJS app. - Then, in index.html we added
<body ng-app="myApp">. Theng-appis called a directive. It tells AngularJS that themyAppmodule will live within the<body>element, termed the application's scope. In other words, we used theng-appdirective to define the application scope. - In MainController.js we created a new controller named
MainController. A controller manages the app's data. Here we use the propertytitleto store a string, and attach it to$scope. - Then, in index.html, we added
<div class="main" ng-controller="MainController">. Likeng-app,ng-controlleris a directive that defines the controller scope. This means that properties attached to$scopeinMainControllerbecome available to use within<div class="main">. - Inside
<div class="main">we accessed$scope.titleusing{{ title }}. This is called an expression. Expressions are used to display values on the page. - The value of
titleshowed up when we viewed the app in the browser.
So far this is our typical workflow when making an AngularJS app:
- Create a module, and use
ng-appin the view to define the application scope. - Create a controller, and use
ng-controllerin the view to define the controller scope. - Add data to
$scopein the controller so they can be displayed with expressions in the view.
- A module contains the different components of an AngularJS app
- A controller manages the app's data
- An expression displays values on the page
- A filter formats the value of an expression
- In the controller, we used
productsto store an array containing two objects. - Then in the view, we added
<div ng-repeat="product in products">. Likeng-appandng-controller, theng-repeatis a directive. It loops through an array and displays each element. Here, theng-repeatrepeats all the HTML inside<div class="col-md-6">for each element in theproductsarray.
In this way,
ng-repeat shows both products in the $scope.products array. Instead of writing the same HTML twice as before, we just use ng-repeat to generate the HTML twice.- The
ng-clickis a directive. When<p class="likes">is clicked,ng-clicktells AngularJS to run theplusOne()function in the controller. - The
plusOne()function gets the index of the product that was clicked, and then adds one to that product'slikesproperty.
Notice that the
plusOne() doesn't interact with the view at all; it just updates the controller. Any change made to the controller shows up in the view.- A user visits the AngularJS app.
- The view presents the app's data through the use of expressions, filters, and directives. Directives bind new behavior HTML elements.
- A user clicks an element in the view. If the element has a directive, AngularJS runs the function.
- The function in the controller updates the state of the data.
- The view automatically changes and displays the updated data. The page doesn't need to reload at any point.
First in js/directives/appInfo.js, we made a new directive. We used
app.directive to create a new directive named 'appInfo'. It returns an object with three options:restrictspecifies how the directive will be used in the view. The'E'means it will be used as a new HTML element.scopespecifies that we will pass information into this directive through an attribute namedinfo. The=tells the directive to look for an attribute namedinfoin the<app-info>element, like this:
The data in<app-info info="shutterbugg"></app-info>infobecomes available to use in the template given bytemplateURL.templateUrlspecifies the HTML to use in order to display the data inscope.info. Here we use the HTML in js/directives/appInfo.html.
Looking at js/directives/appInfo.html, we define the HTML to display details about an app, like its title and price. We use expressions and filters to display the data.
Then in index.html we use the new directive as the HTML element
<app-info>. We pass in objects from the controller's scope ($scope.shutterbugg) into the <app-info> element's info attribute so that it displays.
Why is creating your own directives useful?
- Readability. Directives let you write expressive HTML. Looking at index.html you can understand the app's behavior just by reading the HTML.
- Reusability. Directives let you create self-contained units of functionality. We could easily plug in this directive into another AngularJS app and avoid writing a lot of repetitive HTML.
ng-repeat
We know that AngularJS comes with a few built-in directives like
ng-repeat and ng-click.
We've seen that AngularJS makes it possible to create your own custom directives, such as
<app-info>.
We can use Angular's built-in directives together with custom directives to create more readable apps.
For reference, here's how to use
ng-repeat:<div ng-repeat="product in products"> <img ng-src="{{ product.cover }}"> <p class="title">{{ product.name }}</p> </div>INTERACTIVE DIRECTIVE
- The directive contains the three options
restrict,scope, andtemplateUrlthat we saw before in the'appInfo'directive.
- It also contains a fourth option
link. Thelinkis used to create interactive directives that respond to user actions.
scoperefers to the directive's scope. Any new properties attached to$scopewill become available to use in the directive's template.
elementrefers to the directive's HTML element.
attrscontains the element's attributes.Inside thelinkfunction, there are two propertiesbuttonTextandinstalled, and the functiondownload(). We'll use these in the directive's template next.
We usedapp.directiveto create a new directive named'installApp'.
The link function takes three inputs:
Inside thelinkfunction, there are two propertiesbuttonTextandinstalled, and the functiondownload(). We'll use these in the directive's template next.
- Directives are a powerful way to create self-contained, interactive components. Unlike jQuery which adds interactivity as a layer on top of HTML, AngularJS treats interactivity as a native component of HTML.
WEB SERVICES
- First in js/services/forecast.js, we made a new service. We used
app.factoryto create a new service namedforecast- The
forecastservice needs to use AngularJS's built-in$httpto fetch JSON from the server. Therefore, we add$httpto theforecastservice as a dependency, like this:Now['$http', function($http) { // ... }]$httpis available to use insideforecast.- Then, inside
forecast, we use$httpto construct an HTTPGETrequest for the weather data. If the request succeeds, the weather data is returned; otherwise the error info is returned.- Next in the controller, we used the
forecastservice to fetch data from the server. First we addedforecastintoMainControlleras a dependency so that it's available to use. Then within the controller we usedforecastto asynchronously fetch the weather data from the server and store it into$scope.fiveDay- As before, any properties attached to
$scopebecome available to use in the view. This means in index.html, we can display thecity_nameusing an expression as done before.Why are services useful? Instead of filling the controller with code to fetch weather data from a server, it's better to move this independent logic into a service so that it can be reused by other parts of the app.What can we generalize so far?
- Directives are a way to make standalone UI components, like
<app-info>- Services are a way to make standalone communication logic, like
forecastwhich fetches weather data from a serverROUTINGSo far we've made AngularJS apps that display data in a single view index.html.But what happens when the app grows and needs to display more information? Stuffing more code to a single view will quickly make things messy.A better solution is to use multiple templates that display different pieces of data based on the URL that the user is visiting. We can do this with Angular's application routes.ROUTING - VIEWS
- In app.js inside the
app.config()method, we use Angular's$routeProviderto define the application routes.- We used
.when()to map the URL/to to the controllerHomeControllerand the templatehome.html. TheHomeControlleruses the service js/services/photos.js to fetch the array of all photos from https://s3.amazonaws.com/codecademy-content/courses/ltp4/photos-api/photos.json and stores it into$scope.photos. Thehome.htmlusesng-repeatto loop through each item in thephotosarray and display each photo.- Otherwise if a user accidentally visits a URL other than
/, we just redirect to/using.otherwise().- Now when a user visits
/, a view will be constructed by injectinghome.htmlinto the<div ng-view></div>in index.html.Why are routes useful? Instead of filling a single view with more code than needed, routes let us map URLs to self-contained controllers and templates. Furthermore, now that the app has URLs, users can easily bookmark and share the app's pages.What can we generalize so far?
- Directives are a way to make standalone UI components, like
<app-info>- Services are a way to make standalone communication logic, like
forecastwhich fetches weather data from a server- Routes are a way to manage apps containing more views.
Comments
Post a Comment