Angularjs and ionic frame construction WebApp

Source: Internet
Author: User
Tags install node

This article original copyright to Jane book author chatter Chatter all the chatter, reprint please contact the author to obtain authorization, and at the beginning of the article mark original author and source, show respect!

Wen/chatter, chatter, chatter and chatter (Jane book author)
Original link: http://www.jianshu.com/p/ea0dcf1d31c9
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

AngularJS Introduction: AngularJS is a structural framework designed for dynamic Web applications, providing a new way of developing applications that allows you to extend the syntax of HTML to compensate for the lack of static text when building dynamic Web applications. This allows you to declare dynamic content in a Web application using HTML.

Angularjs has five main core features, which are described below:

two-way data binding --the implementation of the model and view are fully bound together, model changes, view changes, and vice versa.

templates -in Angularjs, templates are equivalent to HTML files being parsed into the DOM by the browser, Angularjs traversing the DOM, which means auguarjs the template as Dom to generate instructions to complete the data binding to the view.

MVVM-absorbs the traditional MVC design pattern needle but does not perform the traditional MVC, much closer to MVVM (Moodel-view-viewmodel).

Dependency Injection --angularjs has built-in dependency injection subsystems that can help developers develop, understand, and test applications more easily.

Directives -can be used to create custom tags or to decorate elements or manipulate DOM properties

Ionic Introduction: Ionic is a powerful _ hybrid/HYBRID_HTML5 Mobile development framework, characterized by the use of standard HTML, CSS and JavaScript to develop cross-platform (currently supported: Android, IOS, program support: Windows iphone, Firefox OS) native app app.


Ionic Introduction

Ionic mainly consists of three parts:

CSS Framework -provides native _app textured CSS style emulation _. Ionic this part of the implementation uses the Ionicons icon style library.

The JavaScript Framework -Ionic is based on the ANGULARJS framework, follows the framework constraints of ANGULARJS, and mainly provides an extension of Angularjs that adapts to the mobile UI, mainly including directives and services. In addition, Ionic uses Angularui router to implement front-end routing.

The command-line/CLI-command-line toolset simplifies application development, construction, and simulation operations. The Ionic command-line tool uses Cordova, which relies on the Platform SDK (Android & IOS) to package mobile Web projects into native apps.

Because Ionic uses some new specifications for HTML5 and CSS3, ios7+/android4.1+is required. Applications developed using ionic on phones that are below these versions sometimes have puzzling problems.

Installing Ionic/install Ionic

First you need to install node. js. Second, install the latest version of Cordova and Ioniccommand-line tools. Install it by referring to the official Android and iOS documentation.

NPM install-g Cordova Ionic

Create a project from Ionic

Create a Ionic app using the ready-made application template provided by ionic, or a blank project.

Ionic start myApp blank Create a blank app item (1)

Ionic Start myApp Tabs create a project with tabs (2)

Ionic start myApp Sidemenu create a project with sliding (3)


above picture

I'm now creating a blank project Ionic start myApp blank


cmd window

Then we see that there is a MyApp project build. The following directory


then open index to run the project.

Then we use the browser to open index to see things like.


Index.html

Next, we use the editor to open the index.html. Observing the documents introduced inside, my habit is to delete files unrelated to the project. You can not delete, I also changed the location of some files, so that you observe the introduction of the file, is afraid you deleted the wrong, the project can not start. The structure of the change is as follows:


Project Structure

Where the configuration files, controller,driectives,filter,services, files are i new.

Let's start with the app.js.


App.js

This myapp needs to be started at the root node. One project suggests one such module.


The above Route config configuration is based on Ui-router, Since the Ionic.bundle.min.js file has been introduced in index.html, this file will pack all the necessary components for angular.js and Ui-router and Ionic, so the reference is convenient.
Open this ionic.bundle.min.js and look at it and know what's being synthesized.


The 6 file package to synthesize one, you can separate Baidu to see what each package, leave you to think.

$stateProvider. State (name, {
URL: ",
Templateurl: ",//This is the template location
Controller: "//This is the controller name of the corresponding template! Remember that the name is not the location
});

The above is the basic usage of ui-router, the details of which can be viewed in the official documentation.

App.js configured, the controller is configured below

We have just finished configuring app.js, we want to create a new name called Homectrl Controller. Naming I suggest Xxxctrl or xxxcontroller, of course, with your project as the standard.


Homectrl

Use the closure mode to create the controller, in order to insure against unnecessary variable pollution errors. which

Angular.module (' myApp ') is loading the module you just created, and then setting up a controller called Homectrl,

The format is generally angular.module (' myApp '). Controller (name, [params, function (params) {}]).

After the Homectrl is created, it is referenced in index.html, such as:


Remember to quote below App.js

Well, we've created the controller based on the route we just configured, and now we have a template.

Create a home template

In the document template folder you just created, create a new home.html. That is, just configure the path and name of the route in App.js, forget to look back to see how App.js is written. In the home.html you just created, write the above content

Such as:


home.html

In the project we wrote that all the <ion-xxx></ion-xxx> is ionic frame. This is an instruction, if you don't understand what the instructions mean, it's okay. You will be treated as a custom label with some features.
After you create the home.html template and Homectrl.js. We tried to start, open the index.html file in the browser, this file as the entry for a project. Ion-view is the top level of this page, all content is in this view, Ion-header is the head, Ion-content is the content. None of this is necessary, but I recommend it because ionic some components need to be in these tags to work. Then see such as:


index.html

When you see the "Hello World" text appearing on both the page and the console, it proves that we succeeded and the project started successfully.

Summary of creating app.js and HTML templates and Homectrl templates

In fact, we write the idea of the project: to cite the example just now

1. Create a app.js, start the project first, then configure the route. Where routing requires template and controller So the problem comes, then look at 2, 3, step.

2. Then create the template, xxx.html the template.

3, finally create the controller xxxctrl.js.

Writing controllers and templates

Here's something interesting, let's start with a carousel diagram. Then use the Ionic framework to bring your own, specific documents can be found, such as:


Add the following HTML

Refresh your browser such as:


more banner.

OK, this proves that we have succeeded, can slide, can be self-made switch. In fact, there are many features that can be consulted in the documentation attempt. Generally because the mobile site banner are read from the background data, then we rewrite. The controller obtains the data, then assigns the value to the $scope variable, because the page and the corresponding controller's $scope has the correlation, therefore the corresponding page the property also will be good , is still not quite clear, then looks at the code. Homectrl as follows:


Homectrl


Home.html

Let's change the code into

1. ng-repeat= "item in Views.slidedata track by $index", meaning to traverse from the $scope.views.slidedata array, item is an item in the array, track by $ Index in fact is performance optimization, subsequent will say, you can also not write directly ng-repeat= "item in Views.slidedata"

2, before by this into

Getting data from the server

Wordy words do not say, directly on the case.


Get Data, Output to List

Since data is needed, it is the most common and flexible way to build a service and create a service using Angular.module's Factory API. In fact, there are several

Factory ()

Service ()

Constant ()

Value ()

Provider ()

, detailed documentation, but most projects use this (factory) creation method to meet the requirements. To give a simple example

The factory () method is the quickest way to create and configure a service. The factory () function can accept two parameters.

Name (String)

The name of the service that needs to be registered.

GETFN (function)

This function is called when ANGULARJS creates a service instance.

Angular.module (' myApp ')

. Factory (' MyService ', function () {

return {

' username ': ' auser '

};

});

To our real example code, OH, like:


This file is the original new servers.

Some students feel strange, how can it be app.factory? In fact, the app is Angular.module (' MyApp ', []), I assign the Angular.module (' MyApp ', []) to the global variable app in the App.js file. See:


App.js

We built the servers. Introduced in Index.html, OH:


index.html

Good! Create a good servers.js and introduce it in index. So how do you call it in the controller? Let's take a look at the rewritten controller,


Homectrl


Control Desk

The Ajax requests that we created from the services to call services were successful, how do we get the data in Homectrl?

Let's start with services rewriting, such as:


Services

Homectrl How to get data? See:


Homectrl

Call the Myfactory.getlist () method Why is it followed by a then? In fact, we use the built-in $http services to communicate directly with the outside. $http service simply encapsulates the native XMLHttpRequest object of the browser. $http Service is a function that accepts only one parameter, which is an object that contains the configuration content used to generate the HTTP request. This function returns a Promise object, and since the $http method returns a Promise object, we can use the then method to handle the callback when the response is returned. If you use the then method, you get a special parameter that represents the success or failure information for the corresponding object, and you can accept two optional functions as arguments. Or you can use the success and error callback instead, as to what the Promise object is, here is not a description, write up a larger space, or leave you to check the document it.

Promise.then (function (RESP) {

RESP is a response object

}, Function (RESP) {

RESP with error messages

});

Or use the Success/error method

Promise.success (function (data, status, headers, config) {

Handling a successful response

});

Error handling

Promise.error (function (data, status, headers, config) {

Handling a non-successful response

});

Then look at the console output what, or look at the picture:


Console displays the calling interface successfully

Ok! is done, we can bind this data to $scope and render it to the page. Or look at the picture:


Homectrl


Home.html


List Changes

Summarize:

1, create services and write the service inside, then introduce services in index.html.

2, Homectrl into the dependency services inside the factory service, call inside the method.

3. Call the factory service method in Homectrl, and then fetch the data. Then assign the data to $scope. So the template can also get the data inside the $scope, then the page data is updated.

Writing filters

The above has taught you how to set up a services service to get data, but sometimes we get the data back to make further changes to the data displayed on the page, below if we have a requirement, I want to capitalize all the names.

1. First, create a filter.

2. Filter is introduced in index.html. (This does not say, please see how the services introduced above)


Filter.js

In the Home.html page, the name is written like this.

Name: {Item. Name | Touppercasetext}}


it's capitalized.

So now I want to turn the city into lowercase, how to do it? Let's leave you a homework.

As you can see earlier, creating a custom filter is very easy. Creating a custom filter requires that it be placed in its own module. A filter is essentially a function that passes what we enter as a parameter. The above is just a simple example, in fact, is to get the data in, the data came in, you want to deal with the data on how to deal with. The equivalent of when you were a child, you cheat your parents pocket money when it comes to your pockets, as to how the money used, it is your own business. When your mom and dad ask you what you're going to do, you tell him that it's equivalent to finishing the data and rendering it on the page. The filter actually has a lot of very good built-in, and when you need it, check the document every now and then. The usage is so simple.

Filter Summary

1, analysis of the need for data on the page, check whether the built-in filter to meet the needs.

2, if the demand built-in filter can not meet, create filter.js, write processing data logic.

3. Introduction of filter in Index.html. In the need to use the filter plus "|", for example: {{item. Name | Touppercasetext}}

Passing Data between pages

When we finish writing the home.html page and complete the Homectrl, and get the data from the backend server through services, we present to the page, proving that we have succeeded in the majority of a small project. You can imagine that a project is to get the data, show the data (as to how to display, click on the display or the default display, which is interactive), or submit the data, submit the data this article does not say, but we already know how to obtain, the submission is still difficult. It's all about the same principle. Go through the documents yourself and see how $http can be solved. We continue to implement a requirement below, click on a list of items just now to jump to the details page.

Create a new detail page detail.html, create a new Detailctrl controller, and configure the Detail page routing. Forget to look at the steps to create a new home earlier. ( remember to introduce Detailctrl in index.html, otherwise you will report the following error, look at the picture )


when we jump detail route, due to not introduce the corresponding Detailctrl, will be error

The following shows the routing configuration and detail.html pages and Detailctrl.js


Routing Configuration
Detailctrl


Detail.html

We configured the Routing and new detail page and controller. We implemented a click-through list to jump to the detail page and bring the data. I repeat, this article with <ion-xxx> are ionic framework, Ion-view is the top layer of this page, all the content in this view, Ion-header is the head, Ion-content is the content. None of this is necessary, but I recommend it because ionic some components need to be in these tags to work.

Then we click on the list

The idea is ng-click= "Views.godetail (item)"; Views.godetail is jump to detail page, jump route using $state.go ("XXX"); XXX represents the name of the route, item is the data you click on an item, look at the graph:


in ng-click,home.html
Homectrl

When we click on the list, we can see that the console prints the contents of the item.


Console.log (item)

Now the need to implement the following detail diagram.


Click Details

How to implement from a page = = "b page, and a page of data to the B page." The following is a discussion of the way data is passed between angular pages. Here are 5 ways, maybe more, but I choose the usual ones.

1, you can use $rootscope top-level scope, from a page assigned to a property of $rootscope, and then B page to get data assignment to the page.


Homectrl


Detailctrl


Detail.html

As a result, the details page can achieve the effect just now.

2, in a page with $state.go ("xxx", {obj}), configure the routing parameters, and then on the B page with the $stateparams object to get the parameters of the URL.


Homectrl,item is either an object or a string



Detailctrl


Use this method to pass the URL from the home page.

3, in the services to establish a service, on a page to the data to the service, and then on the B page to get the value of the service. Why do you do this? Because the methods inside the Services service are shared, services are instantiated once when the project is initialized (the service is a singleton object that is instantiated only once in each application (instantiated by the $injector) and is deferred (created only when needed) ), so there is no jump page on the data. (This is the best practice, but it also depends on the business scenario.) This is the one I used the most).


Services.js


Homectrl Setting values


Detailctrl


detail.html


Detail.html

The transfer data between pages, the above is commonly used in 3 kinds. The following are not so commonly used:

Use Localstorage, sessionstorage, cookies to store a value in page A, and then get the value in page B, all 3 of which are stored data. The difference between them you check the document, Ha ha ~ ~ ~ Left you to think.

Data binding

Data binding, getting the data from the service from the beginning, then binding the data to $scope, and then typing the {{}} curly brace out of the page, which is data binding. So let's assume that there is an input box, what is the input box, and what is the age of the person in the list.

Because of this need, is bidirectional data binding, you can ng-model with a variable, the variable is assigned to the age, then the age also changed. See:


Detailctrl.js


detail.html


page Display

OK, OK, the initialization is done. Now, let's change the value in the input box to see what's changed by inputting the box value in input.

Changed the

The value in the input box has changed, and the above age value has changed. To prove that the value of $scope.views.age has changed, these are data bindings.

Data Binding Summary

When Angularjs thinks a value may change, it runs its own event loop to check whether the value is "dirty". If the value has changed since the last event loop was run, the value is considered a "dirty" value. This is also how angular can track and respond to application changes. This event loop calls the $digest () loop (which you'll find out if you check the documentation). This process is called a dirty check (dirty checking). Dirty checking is an effective means of checking data model changes. When there is a potential change, ANGULARJS performs a dirty check (lookup document) during the event loop to ensure data consistency.

Angularjs and Ionic framework build WebApp

Related Article

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.