AngularJS introduction: AngularJS is an architectural framework for dynamic WEB applications that allows you to declare dynamic content in your WEB applications using HTML by extending the syntax of HTML to compensate for static text when building dynamic WEB applications.


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

Two-way data binding – Fully binding model and View, model changes, view changes, and vice versa.

Templates – In AngularJS, templates are the equivalent of HTML files that are parsed into the DOM by the browser. AngularJS traverses the DOM, which means AuguarJS operates on the template as a DOM and generates instructions to perform data binding on the view.

MVVM – assimilates the traditional MVC design pattern but does not implement MVC in the traditional sense. It is closer to MVVM(Moodel-view-ViewModel).

Dependency Injection – AngularJS has a built-in dependency injection subsystem that makes it easier for developers to develop, understand, and test applications.

Directive – can be used to create custom tags, decorate elements, or manipulate DOM attributes


Ionic is a powerful hybrid /hybrid_HTML5 mobile development framework, featuring the use of standard HTML, CSS and JavaScript, developed across platforms (currently supported: Android, iOS, planned support: Windows Phone, Firefox OS).







Introduction of ionic

Ionic consists of three main parts:

CSS framework – provides native _App texture CSS style emulation _. The ionic part of the implementation uses the IonIcons style library.

JavaScript Framework – Ionic is based on the AngularJS framework and follows the AngularJS framework constraints; AngularJS extensions for mobile UIs, including directives and services. Ionic also uses AngularUI Routers for front-end routing.

Command line /CLI- The command line tool set is used to simplify application development, construction, and emulation. Ionic command line tools use Cordova and rely on the platform SDK (Android & iOS) implementation to package mobile Web projects as native apps.

Ionic requires iOS7+/Android4.1+ because it uses some new specifications for HTML5 and CSS3. Using apps developed in the Ionic on phones with versions lower than these can sometimes cause baffling problems.


Install the ionic/Install ionic

First, 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 with Ionic

Create an Ionic app using either the ready-made app template provided by Ionic officially, or a blank project.

Ionic Start myApp Blank Creates a blank app project

Ionic Start myApp Tabs Create a project with tabs

Ionic Start myApp Sidemenu creates a project with a slide






The above picture

I will now create a blank project ionic Start myApp Blank






CMD window

Then we see the myApp project being generated. The following directory






Then open index to run the project

Then we open index in the browser and see the following image.






index.html

Next, we use the editor to open index.html. Looking at the files introduced, IT is my habit to delete files that are not relevant to the project. You don’t have to delete it. I also changed the location of some files. The reason why I asked you to observe the files introduced in it is for fear that if you delete the wrong files, the project will not start. The modified structure is as follows:





The project structure

The configuration files, Controller, Driectives, filter,services files are all created by me.

Let’s start with app.js






app.js

This myApp needs to start at the root node. A project suggests one such module.






The route config configuration above is based on the UI-router. Since ion.bundle.min. js has been introduced in index.html, this file packs angular.js and uI-Router and ionic components, so it is easy to reference. Take a look at ionic. Bundle.min. js to see what you’ve made.






Now that you’ve combined the 6 packages into one, you can search for each package and leave it for you to think about.

$stateProvider. State (name, {url: “, templateUrl: “, templateUrl: “, // Remember names, not locations});

These are the basic uses of the UI-router. For details, see the official documentation.

After app.js is configured, let’s configure the controller

Now that we’ve finished configuring app.js, we’re going to create a new controller called homeCtrl. I suggest XXXCtrl or XXXController, of course, for your project.






homeCtrl

Controllers are created in closure mode to insure against unnecessary variable contamination. Among them

Angular. module(‘myApp’) loads the module you just created and sets a controller called homeCtrl,

Module (‘myApp’). Controller (name, [params, function(params) {}]).

After homeCtrl is created, reference it in index.html as shown below:






Remember to reference it in app.js

Ok, we have created the controller based on the route we just configured, now we just need the template.

Create the Home template

Create a new home.html file in the document template folder. This is the path and name of the route in app.js configuration. If you forget, go back to app.js. In the home.html you just created, write the above

The diagram below:





home.html

In the project we say that anything with < ion-XXX >
comes with the Ionic framework. It’s an instruction, and if you don’t know what an instruction means, that’s fine. Think of it as a custom tag with some functionality. After creating the home.html template and homectrl.js. We try to start by opening the index.html file in a browser, which acts as an entry point for a project. Ion-view is the top layer of this page, so everything is in this view, ion-header is the header, ion-content is the content. None of this is required, but I recommend it, because ionic has some components that need to be in these labels for it to work. Then you see the picture below:






index.html

When “Hello World” appears on both the page and console, it proves that we have succeeded and the project has started successfully.

Create app.js and HTML templates and homeCtrl template summary

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

1. Create app.js, first start project, then configure route. Routing requires a template and a controller so the problem is going to be step 2, step 3, step 3.

2. Then create a template, the XXX.html template.

3, finally create xxxCtrl. js controller.

Write controllers and templates

Now, let’s do something interesting. Let’s do a rotation diagram. Use the ionic framework that comes with it. For details, check out the documentation below:






Add the following HTML

Refresh the browser as shown below:






More than the banner

Okay, so that proves that we’ve done it, you can slide, you can toggle. In fact, there are a lot of features, you can check the documentation to try. Generally because the mobile website banner is from the background to read the data, so let’s rewrite. Fetch the data in controller and assign it to the $scope variable. Since the page is associated with the controller’s $scope, the properties on the corresponding page will also get better. HomeCtrl is as follows:






homeCtrl






home.html

Let’s change the code to

1, ng-repeat=”item in views.slidedata track by $index”, $scope.views. SlideData array, $scope. Ng-repeat =”item in views.slidedata “track by $index is a performance optimization. You can also use ng-repeat=”item in views.slidedata”

<img SRC =” path “> becomes <img ng-src=”{{item}}”, where ng-src is an Angular directive and item is the path traversed by the array

Get data from the server

Let’s cut the long-winded words and go straight to the case. As shown in figure:






To get the data, output to the list


Creating a service using the Angular. module factory API is the most common and flexible way to do this. There are actually several

factory()

service()

constant()

value()

provider()

Check the documentation for details, but most projects will do just fine using this factory creation method. Let’s take a simple example

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

Name (string)

The name of the service to be registered.

GetFn (function)

This function is called when AngularJS creates the service instance.

angular.module(‘myApp’)

    .factory(‘myService’, function() {

        return {

            ‘username’: ‘auser’

        };

    });

It’s time for our real example code, as shown below:






This file is the newly created Servers.


Some students feel strange, how can it be app. Factory? Module (‘myApp’,[]). I assigned angular.module(‘myApp’,[]) to the global variable app in app.js. See below:






app.js

We’ve built the Servers. Add to index. HTML:






index.html

Good! Create servers.js and introduce it in index. So how do you call it in controller? Let’s take a look at the rewritten controller, as shown below:






homeCtrl






The console

How do we get data from homeCtrl after we have successfully created the service and called the Ajax request inside the service?

Let’s start with the “services” rewrite as shown below:






services

How does homeCtrl get data? See below:






homeCtrl

Myfactory.getlist () is followed by a then. Instead, we use the built-in $HTTP service to communicate directly with the outside world. The $HTTP service simply wraps the browser’s native XMLHttpRequest object. The $HTTP service is a function that accepts only one parameter, which is an object containing 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 returns. If you use the then method, you get a special argument that represents the success or failure of the corresponding object, and you can take two optional functions as arguments. Or you can use success and error callbacks instead. As for what promise objects are, I won’t describe them here, but I’ll leave them to the documentation.

promise.then(function(resp){

// Resp is a response object

}, function(resp) {

// ResP with error message

});

// Or use the success/error method

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

// Process a successful response

});

// Error handling

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

// Process unsuccessful responses

});

Then take a look at the console output, again at the picture:





The console shows that the interface was successfully invoked

OK! That’s it. We can bind this data to $scope and render it to the page. Or look at the picture:






homeCtrl







home.html






A list of changes

Conclusion:

1, Create the services and write the services inside, and then import the services in index.html.

2, homeCtrl injection dependency services inside the factory service, call the method inside.

3. Call the Factory service method in homeCtrl and get the data. Assign the data to $scope. So the template can also fetch data from $scope, and the page data is updated.

Writing filters

We’ve already taught you how to create a “Services” service to get data, but sometimes we get data back and the data is further modified to show up on the page. If we have a requirement, I want to change the name to all caps.

1. Create a filter.

2. Add filter to index.html. (This is not to say, please see above how to introduce services)






filter.js

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

Name: {{item. The Name | toUpperCaseText}}






It becomes uppercase

So now I want to make the city lowercase. How do I do that? I’ll leave you with a homework assignment.

As you saw earlier, creating custom filters is very easy. Creating a custom filter requires placing it in your own module. A filter is essentially a function that takes our input as an argument. So this is just a simple example of getting the data in, and when the data comes in, you can do whatever you want with the data. It’s like when you’re a kid, you cheat your mom and dad out of an allowance, and the money goes to you, and what you do with it is your own business. When your mom and dad ask you what to do with it, and you tell him, it’s like processing the data and rendering it on the page. The filter actually has a lot of very useful built-in, need to check the document from time to time on the line. Usage is that simple.

Filter summary

1. Analyze the data required on the page and check whether the built-in filter meets the requirements.

2. Create filter.js and write the logic to process data if the requirement of built-in filters cannot be met.

3. Introduce filters in index.html. In the need to use the filter with “|”, for example: {{item. The Name | toUpperCaseText}}


Data is passed between pages

When we finish writing the home.html page and complete the homeCtrl, and get the data from the backend server through the Services and show it to the page, we have succeeded in most of a small project. As you can imagine, a project is all about getting data, showing it (how to show it, click show or default show, it’s an interactive thing), or submitting the data, submitting the data, this article doesn’t say, but we already know how to get it, so it’s hard to submit. It’s the same principle. Check out the documentation for the $HTTP method. To implement a requirement, click on one of the items in the list to jump to the details page.

Create a detail page detail. HTML, create a detailCtrl controller, and configure the detail page route. If you forgot, look at the previous steps to create a new home. (Remember to introduce detailCtrl in index. HTML, otherwise the following error will be reported, look at the image)






When we jump to the detail route, an error is reported because the corresponding detailCtrl is not introduced

The route configuration and detail. HTML page and detailCtrl.js are shown below






The routing configuration





detailCtrl






detail.html

We’ve configured the route and created the detail page and controller. We implemented clicking on the list to jump to the detail page and bring the data. Once again, ion-xxx comes with the Ionic framework. Ion-view is the top layer of this page. All the content is in this view. None of this is required, but I recommend it, because ionic has some components that need to be in these labels for it to work.

So let’s click on the list

Ng-click =” views.godetail (item)”; $state. Go (“XXX”); XXX stands for the name of the route, and item is the data you click on an item.






Ng – click home. In the HTML





homeCtrl

So when we click on the list, we can see that the console prints out the contents of the item.






console.log(item)

Now you need to implement the following detail diagram.






Click on the details

How to realize from page A == page B, and bring the data from page A to page B. Let’s explore how Angular pages pass data between them. Here are five ways to do it, there may be more, but I’m going to go with the common ones.

$rootScope = $rootScope = $rootScope = $rootScope = $rootScope = $rootScope = $rootScope = $rootScope






homeCtrl






detailCtrl






detail.html

As it turns out, the detail page does exactly what you were expecting.

$state. Go (” XXX “, {obj}); Configure the route parameters, and then get the URL parameters using the $stateParams object on the B page.






HomeCtrl,item is an object,it can be a string










detailCtrl







The URL passed from the home page using this method

Create A service in services, pass data to the service on page A, and get the value of the service on page B. Why can you do that? Since the methods in the Services service are shared, the services have already been instantiated once when the project is initialized (the service is a singleton and has only been instantiated once per application (instantiated by $Injector) and is lazy-loaded (created when needed). So if there’s no jump page, there’s no data. (This is a best practice, but it also depends on the business scenario. This is the one I use the most).






services.js






The setting of the homeCtrl






detailCtrl






detail.html







detail.html

Data transfer between pages, the above are the three commonly used. Here are the less common ones:

Use localStorage, sessionStorage, cookie to store value in A page, and then get value in B page, these three can store data. The difference between them you check the document, ha ha ha ~~~~ to leave you thinking.

Data binding

Data binding: start by fetching data from the service, bind it to $scope, and print it in curly braces on the page. So let’s say we have an input field, and what is the input field, and what is the age of the person in the list.

Because of this requirement, known as bidirectional data binding, ng-model can bind a variable that is assigned to the age, and the age changes as well. See below:






detailCtrl.js







detail.html






Page shows


All right, all right, initialization is done. Now, in the input field, let’s change the value in the input field and see what happens.

Changed the

The values in the input box have changed, and the age values above have changed. Prove that the value of $scope.views.age has changed. These are data bindings.

Data binding Summary

When AngularJS thinks a value might have changed, it runs its own event loop to check if the value has become “dirty.” The value is considered dirty if it has changed since the last time the event loop was run. This is how Angular can track and respond to application changes. This event loop calls the $digest() loop (check the documentation for this). This process is called dirty checking. Dirty checking is an effective means of checking for changes in the data model. When there are potential changes, AngularJS performs dirty checks (looking up documents) during the event loop to ensure data consistency.

Source code: Baidu network disk http://pan.baidu.com/s/1i59P1cD

Suppose you open the source code. I write more ugly don’t laugh at me, there may be some mistakes inside, hope correct, my QQ1142829292 won’t, if I have time can exchange.

If you read the source code you will report these errors, the first error is because I did not introduce Cordova, and the second error is because the CSS source fonts are missing. (The problem is in the small circle of the home page, you can actually write a style to eliminate it, the problem can be solved)

Recently I am looking for a job, but it is painful. Guangzhou friends have







Did this article help you? Welcome to join the front End learning Group wechat group: