Angular Getting Started

Source: Internet
Author: User

Angular Getting Started

This series will cover a total of two JavaScript frameworks, one is express for the backend, and the other is angular for the front end. Like Express, angular separates content and processes views, data, and logic. Similar to the MVC pattern, but in fact the angular definition is the MVW framework, W represents (what ever works for you). It means that it can be a controller or a view model, or a service, and it depends on how you define it. This section introduces basic angular knowledge, then changes the page we made earlier, and invokes the previously defined API to get the data.

Angular data binding means that changes to the view will update the model, and the changes to the model will also update the view.

It's not like we're using jquery to bind DOM events and then change the DOM. Similar to two-way binding in WPF.

One, the first example: data binding first experience

You may have seen a lot of such examples, but don't worry, we are gradual.

<input/>
How do I make the input in input appear immediately after Hello? If JavaScript or jquery is a natural binding keystroke event, however, angular does not need to write JavaScript code anymore. First introduce
<script src= "Angular.min.js" ></script> or <script src= "http://apps.bdimg.com/libs/angular.js/1.4.6/ Angular.min.js "></script>

Then we also need to tell angular that this page is a angular application, which is the HTML tag modified as follows:

Ng-app This attribute can actually be added to any element, which marks the scope of the angular. Added to the HTML, which means that the entire page angular can work. Next we will bind input to a model: Myinput,
<input ng-model= "Myinput"/>

Next, put the model where we want to output it, and angular use {{}} to bind. As below, the names of the two places here must be the same.

The rest will be handed to angular to do, demo:

This is consistent with the meaning expressed in the first picture, the changes to the view update the model, and the changes to the model update the view.

Second, set the model initial value

After feeling the magic of angular, learn more about angular by giving the model an initial value. To achieve this, we need to create a angular application module, a controller to manage scopes.

1.module

The name of the module is used for the Ng-app property of the label. Create a new JavaScript file, defined as follows:

Angular.module (' myApp ', []);

This affirms a angular application module for the

2.controller

With the module, you can define the controller, which is defined in JavaScript code and attached to an HTML element to indicate that it works inside this element. As below, we attach the controller to the body, named Mycontroller:

<body ng-controller= "Mycontroller" >

Look at the JavaScript section again:

function Mycontroller () {    };angular.module (' myApp '). Controller (' Mycontroller ', mycontroller);

A ' mycontroller ' is defined and added to the ' myApp ' module. Next we give the model an initial value through scope.

3.scope

Like JavaScript code, angular also has scopes, and angular has a rootscope, similar to the global scope in JavaScript, that contains the entire application. Rootscope contains one or more child scopes, such as the Ng-controller directive, which creates a child scope. Scopes are associated with views, models, and controllers. The Mycontroller method defined above can take a $scope parameter and must be the name. It represents the scope and angular has been created automatically. The model can be obtained by this parameter. In this way, setting the initial value is simple:

var mycontroller = function ($scope) {    $scope. myinput = "angular!";};

This feeling is dependent on injection, $scope provided by $scopeprovider. Then look at the effect:

Both the input box and the H1 element appear with the initial value of the model.

Third, the page transformation

Angular is a JavaScript file that runs on the client, and we need to tell the express framework that it can be used as a static file transfer when requesting a angular script file, without having to run it. The public folder is already set to static.

App.use (Express.static (Path.join (__dirname, ' public '));

So you can create a new angular folder under the public file, place the angular script file, and create a new readapp.js. Define in the inside:

Angular.module (' Readapp ', []);

Then add the files in the Layout.jade:

    Script (src= '/angular/angular.min.js ')    script (src= '/angular/readapp.js ')
HTML (ng-app= ' Readapp ')

This means that all pages support angular. But if you want to use angular to show the data, then angular have to get the data first (no more using Jade to render the view), this has three steps

1) Remove the call from the API in the corresponding home controller in Express.

2) Add the encoding to the scope of the angular application.

3) Update the view template and bind to the angular data.

The first step, you can comment out the index method in the request API code, directly return to the view, to angular out of the scene.

Module.exports.index = function (req, res) {    //var requestoptions, path;    Path = "/api/topics";    Requestoptions = {    //    url:apiOptions.server + path,    //    method: "GET",    //    JSON: {},    //}    //request (requestoptions, function (err, response, body) {    //    if (Response.statuscode = =) {    //        res.render (' index ', {title: ' Index ', topics:body});    } else {    //        res.render (' error ', {message:err.message, error:err});    //    }    //});    Res.render (' index ', {title: ' Index '});

The second step is to add a controller to the Readapp.js, first with the static data:

View Code
var HomeController = function ($scope) {    $scope. data = topics;};

and register:

Angular.module (' Readapp ')    . Controller (' HomeController ', HomeController)

Step three: Update the view (Index.jade)

   . Col-md-9.page (ng-controller= "HomeController")     . Row.topictype       a.label.label-info (href= '/')  all       A (href= '/') reading       A (href= '/') book review A (       href= '/') book       A (href= '/') Quest     . Row.topiclist (ng-repeat= ' topic in data ') )          img (ng-src= ' {topic.img}} ')          Span.count            i.coment {{Topic.commentcount}}            I/            I {{ Topic.visitedcount}}          span.label.label-info {{Topic.type}}          A (href= '/') {{topic.title}}          span.pull-right {{topic.createdon|formdate}}          A.pull-right.author (href= '/') {{Topic.author}}

We will homecontroller load the. Page on this element. In the second step, we define a data model, which is actually a collection of arrays, where

(ng-repeat= ' topic in data ')

Loop output. Instead of the each syntax of Jade: 'each topic in topics ', unlike Jade, the circular statement of Jade is located above the. Topiclist, and the angular repeat instruction is added to the element you need to repeat. It is also important to note that all elements in the content of the {{}} before the equal sign to be taken out, the space to assign the syntax (the equals sign variable, the space is a string), otherwise it cannot be output. Again note that one is IMG src to use NG-SRC, otherwise cannot output URL. This time, you can see the output:

4.filter

You may notice that there is a code like this:

{{Topic.createdon|formdate}}

After the property is followed by a | number and a name, which is called the filter, so the name Incredibles, through the specific rules, the source data into the desired data format . The definition of formdate here is:

var formdate = function () {    return function (datestr) {        var date = new Date (DATESTR);        var d = date.getdate ();        var monthNames = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "Ten", "one", "one"];        var m = Monthnames[date.getmonth ()];        var y = date.getfullyear ();        var output = y + '-' + M + '-' + D;        return output;    };}; Angular.module (' Readapp ')    . Controller (' HomeController ', HomeController)    . Filter (' Formdate ', formdate)

Formal and registered controller is the same, the difference is that thefilter needs to return a function . In fact, angular bring some data format, such as Data,currency and so on. As follows

<div>{{50.25|currency}}</div>$50.25 <div>{{50.25|currency: ' ¥ '}}</div>¥50.25
    <div>{{"Let ' s shout" | uppercase}}</div>    <!--output: Let's shout--    {{timestamp | date: "D MMM yyyy "}}    <!--output: £ º
5.directive

Directives are primarily used to create HTML fragments, and an HTML snippet can be used by several different controllers and view, which is easily consistent and easy to maintain. These fragments run in the context of the angular application, so data binding can be used, and the browser can cache these instructions as HTML files, which helps to speed up the application when the user switches back and forth between different view. Next, we show you how to add a directive that changes the part of the star before it is changed (switch to Books.jade).

First simulation data, add models in HomeController

  $scope. Models = [{Rating:4}, {rating:5}];

Then define a ratings directive:

var ratingstars = function () {    return {        Template: "{{book.rating}}",    };};

and register,

Angular.module (' Readapp ')    . Controller (' HomeController ', HomeController)    . Filter (' Formdate ', formdate)    . directive (' Ratingstars ', ratingstars)

Output on the view. Here is a note that the HTML attribute is case insensitive, the hump-type naming needs to be converted, that is, the Ratingstars match is Rating-stars, that is, uppercase letters to the '-' plus lowercase letters.

P (ng-repeat= ' book in Models ')      Small (rating-stars)

4 and 5 are output on the page. This is not enough to meet our requirements. There are two points: 1 attribute name limits are too dead to be always ' book.rating '. 2 is the need to turn numbers into stars. The first problem is a scope problem that requires a scope variable to be created.

return {        scope: {            thisrating: ' =rating '        },        Template: ' {{thisrating}} '    };

A thisrating scope variable is created, and ' =rating ' tells angular to match the attribute with ' rating '. Then create a rating-stars.html under the angular folder.

<span class= "Glyphicon glyphicon-star{{thisrating<1? '-empty ': '}} ' ></span><span class= ' Glyphicon glyphicon-star{{thisrating<2? '-empty ': '}} ' ></span><span class= ' Glyphicon glyphicon-star{{thisrating<3? '-empty ': '}} ' ></span><span class= ' Glyphicon glyphicon-star{{thisrating<4? '-empty ': '}} ' ></span><span class= ' Glyphicon glyphicon-star{{thisrating<5? '-empty ': '} ' ></span>

and point to this fragment with Templateurl.

var ratingstars = function () {    return {        scope: {            thisrating: ' =rating '        },        templateurl: '/angular/ Rating-stars.html '    };

Apply on the view:

P (Rating-stars, rating=book.rating)

Get the Stars

This scope of the directive is not very convenient. The first use of the simulation data is because small (rating-stars) does not recognize the book object in the loop in Jade, which is in books, and ' P (rating-stars, rating=book.rating) ' and can be identified.

6.service

Service is used more in angular, most of the application logic can be implemented with service, and can be called to multiple controllers. Next, move the controller's data into a service and let the controller invoke the service.

Create a method named Topicdata to return the topic data.

var topicdata = function ($http) {      return topics;};

Register Service:

. Service (' Topicdata ', topicdata);

Using service:

var HomeController = function ($scope, topicdata) {    $scope. data = Topicdata;};

Don't forget to include the name of the service you want to invoke in the parameter. Now that we have completed a call to the service, we are going to get the data from the API. JavaScript sends HTTP requests is nothing new, jquery's Ajax,node inside the request module, and angular has a self-contained service: $HTTP, to handle requests. Next, use it to request the API.

var topicdata = function ($http) {   return $http. Get ('/api/topics ');};

$http has a Get method, the parameter is a URL. Here we call the API defined in section three. Create models and APIs with Mongoose

This is an asynchronous approach, so you need to transform the code in the controller:

var HomeController = function ($scope, topicdata) {      topicdata.success (data) {        console.log (data);        $scope. data = data;    }). Error (function (e) {        console.log (e);       });

At this time, you can see all the data.

One problem with loading data asynchronously is that the user may be blank when the page is opened, so adding a transition content is a bit better.

var HomeController = function ($scope, topicdata) {    $scope. Message = "Loading ...";    Topicdata.success (function (data) {        console.log (data);        $scope. Message = data.length > 0? "": "No data";        $scope. data = data;    }). Error (function (e) {        console.log (e);        $scope. Message = "Sorry, something ' s gone Wrong";});

Page Plus One:

. Error {{message}}

This avoids a short space of time.

Summary: In this section we experience the angular data binding pattern and learn how to define and use module, Controller, Directive, filter, and service. Simply transformed the home page, transferring part of the work to the front end of the Express. In fact, each part of the angular involved is not deep enough, just on demand, how much to say how much. I think it's better to be gradual. In the next section you will learn about using angular as a single page application (SPA) to explain angular routing.

Angular Getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.