Home Web Front-end JS Tutorial AngularJs 60-minute basic tutorial for getting started_AngularJS

AngularJs 60-minute basic tutorial for getting started_AngularJS

May 16, 2016 pm 03:06 PM

AngularJs is a good framework for developing SPA applications (single page web applications). A single page web application (SPA) is an application with only one web page. The browser will load the necessary HTML, CSS and JavaScript at the beginning. All operations are completed on this page, and JavaScript controls the presentation of different views on this page. This article originates from a good introductory tutorial video on AngularJs on Youtube: AngularJS Fundamentals In 60-ish Minutes, which mainly explains the concepts and usage of Directive, Data Binding, Filter and Module in AngularJs. Personally, I think these four concepts are the core of AngularJs and support the skeleton of AngularJs. Mastering them is very helpful for understanding AngularJs overall. Advancement requires a lot of practice and reading of the official API documentation.

Look at the picture below to roughly understand what AngularJs is capable of.


First download angular.min.js and angular-route.min.js from the official website. Can be downloaded from the official website (https://angularjs.org/ or https://code.angularjs.org/)

Create an empty Empty Web project in VS.


Directive and Data Binding

The concept of Directive in AngularJs is not easy to understand. In the entry stage, it can be understood as a tag used to extend HTML. Angularjs will parse these tags to realize the Magic of Angularjs.
The following code uses two Directives: ng-app and ng-model.

ng-app: An AngularJs application for auto-bootstrap. This is a necessary Directive, usually added to the root object of HTML (as shown in the following code). For a more detailed explanation, please visit the official website: https://docs.angularjs.org/api/ng/directive/ngApp

ngModel: Used to establish a two-way Data Binding between the property and the HTML control (input, select, textarea), which means that the value change of the HTML control will be reflected on the property, and vice versa. Property is an object created through {{}}.

The following code shows the establishment of Data Binding between the text control and name.

1

2

3

4

5

6

7

8

9

10

11

12

<!DOCTYPE html>

<html ng-app>

<head>

<title>Using Directives and Data Binding Syntax</title>

</head>

<body>

<div class="container">

Name: <input type="text" ng-model="name" /> {{name}}

</div>

<script src="angular.min.js"></script>

</body>

</html>

Copy after login

Directive can be prefixed with "x-" or "data-". Directives can be placed in element names, attributes, classes, and comments.

1

2

3

4

5

6

7

8

9

10

11

12

<!DOCTYPE html>

<html data-ng-app="">

<head>

<title>Using Directives and Data Binding Syntax</title>

</head>

<body>

<div class="container">

Name: <input type="text" data-ng-model="name" /> {{name}}

</div>

<script src="angular.min.js"></script>

</body>

</html>

Copy after login

The following is the result after running the HTML.

The following example shows the usage of traversing an array through ng-init and ng-repeat.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<!DOCTYPE html>

<html data-ng-app="">

<head>

<title>Iterating with the ng-repeat Directive</title>

</head>

<body>

<div class="container" data-ng-init="names = ['Terry','William','Robert','Henry']">

<h3>Looping with the ng-repeat Directive</h3>

<ul>

<li data-ng-repeat="name in names">{{name}}</li>

</ul>

</div>

<script src="angular.min.js"></script>

</body>

</html>

Copy after login

For more usage of directve, please refer to the official website https://docs.angularjs.org/api

Filter

The function is to receive an input, process it through a certain rule, and then return the processed result. It is mainly used to filter arrays, sort elements in arrays, format data, etc.

AngualrJS has some built-in filters, they are: currency (currency), date (date), filter (substring matching), json (formatted json object), limitTo (limit number), lowercase (lowercase), uppercase (uppercase), number (number), orderBy (sort). Nine types in total. In addition, you can also customize filters, which is powerful and can meet any data processing requirements.

The following code shows the implementation of data filtering, sorting and case conversion. Each Filter follows the data and is separated by |.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<!DOCTYPE html>

<html data-ng-app="">

<head>

<title>Using Filter</title>

</head>

<body>

<div class="container" data-ng-init="customers = [{name:'Terry Wu',city:'Phoenix'},

{name:'Terry Song',city:'NewYork'},{name:'Terry Dow',city:'NewYork'},

{name:'Henry Dow',city:'NewYork'}]">

Names:

<br />

<input type="text" data-ng-model="name" />

<br />

<ul>

<li data-ng-repeat="cust in customers | filter:name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city | lowercase}}</li>

</ul>

</div>

<script src="angular.min.js"></script>

</body>

</html>

Copy after login

运行的结果:


Module

Module就是一个容器,用于管理一个AngularJS应用的各个部分,是AngularJS中很重要的概念。一个AngularJS应用就是一个Module,其作用和C#应用程序中Assembly作用类似。C#中我们通过main函数来bootstrap应用程序。而AngularJS则通过na-app="moduleName"的方式来bootstrap一个AngularJS应用。moduleName就是Module对象的name.

下图是一个Module有哪些常见部分组成。

Config/Route:用于配置AngularJS应用的路由(AngularJS),作用类似于ASP.NET MVC应用中的Config/Route。
Filter:对数据起过滤作用,上文有解释。

Directive: 扩展HTML,AngularJS中最重要的概念。没有Directive就没有AngularJS。

Controller: 作用类似于ASP.NET MVC应用中的Controller。页面逻辑就在Controller中实现,通过controller可以对model进行操作。 AngularJS则通过内建的Data-Binding机制将model绑定到view(HTML控件)

Factory/Service/Provider/Value: 提供对数据源的访问。比如Restful API就是常见的数据源。 Controller通过Factory/Service/Provider/Value访问数据源完成数据的CRUD操作。

下面这段代码实现了上面实例的相同的功能,差异就在于这个实例通过创建一个module(angularJS应用),并在module下添加contorller来实现上面的功能。在SimpleController(Controller)中,我们创建了customers(Model)并进行数据初始化, View(Html控件)则直接绑定到customers(Model)。Scope是一个AngualrJS中所有viewModule的容器对象。Controller需要通过Scope是一个AngualrJS中所有viewModule的容器对象。Controller需要通过Scope来访问viewModule。

这个例子比上面例子更接近实际工程中的用法。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

<!DOCTYPE html>

<html data-ng-app="demoApp">

<head>

<title>Using module Controller</title>

</head>

<body>

<div data-ng-controller="SimpleController">

Names:

<br />

<input type="text" data-ng-model="name" />

<br />

<ul>

<li data-ng-repeat="cust in customers | filter:name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city | lowercase}}</li>

</ul>

</div>

<script src="angular.min.js"></script>

<script>

var demoApp = angular.module("demoApp", []);

demoApp.controller("SimpleController", function ($scope) {

$scope.customers = [

{ name: 'Terry Wu', city: 'Phoenix' },

{ name: 'Terry Song', city: 'NewYork' },

{ name: 'Terry Dow', city: 'NewYork' },

{ name: 'Henry Dow', city: 'NewYork' }

];

});

</script>

</body>

</html>

<!DOCTYPE html>

<html data-ng-app="demoApp">

<head>

<title>Using Controller</title>

</head>

<body>

<div data-ng-controller="SimpleController">

Names:

<br />

<input type="text" data-ng-model="name" />

<br />

<ul>

<li data-ng-repeat="cust in customers | filter:name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city | lowercase}}</li>

</ul>

</div>

<script src="angular.min.js"></script>

<script>

var demoApp = angular.module("demoApp", []);

var controllers = {};

controllers.SimpleController = function ($scope) {

$scope.customers = [

{ name: 'Terry Wu', city: 'Phoenix' },

{ name: 'Terry Song', city: 'NewYork' },

{ name: 'Terry Dow', city: 'NewYork' },

{ name: 'Henry Dow', city: 'NewYork' }

];

}

demoApp.controller(controllers);

</script>

</body>

</html>

<!DOCTYPE html>

<html data-ng-app="demoApp">

<head>

<title>Using Controller</title>

</head>

<body>

<div>

<div data-ng-view=""></div>

</div>

<script src="angular.min.js"></script>

<script src="angular-route.min.js"></script>

<script>

var demoApp = angular.module('demoApp', ['ngRoute']);

demoApp.config(function ($routeProvider) {

$routeProvider

.when('/',

{

controller: 'SimpleController',

templateUrl: 'Partials/View1.html'

})

.when('/view2',

{

controller: 'SimpleController',

templateUrl: 'Partials/View2.html'

})

.otherwise({redirectTo:'/'});

});

var controllers = {};

controllers.SimpleController = function ($scope) {

$scope.customers = [

{ name: 'Terry Wu', city: 'Phoenix' },

{ name: 'Terry Song', city: 'NewYork' },

{ name: 'Terry Dow', city: 'NewYork' },

{ name: 'Henry Dow', city: 'NewYork' }

];

$scope.addCustomer = function () {

$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });

};

}

demoApp.controller(controllers);

</script>

</body>

</html>

Copy after login

下图展示了Module及其各个组成部分的关系。

下面实例通过config配置module的route实现一个SPA实例。首先创建View1.html 和View2.html。 目录结构如下图.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<div>

<h2>View1</h2>

Names:

<br />

<input type="text" data-ng-model="filter.name" />

<br />

<ul>

<li data-ng-repeat="cust in customers | filter:filter.name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city | lowercase}}</li>

</ul>

<br />

Customer Names:<br />

<input type="text" data-ng-model="newCustomer.name" />

<br />

Customer City:<br />

<input type="text" data-ng-model="newCustomer.city" />

<br />

<button data-ng-click="addCustomer()">Add Customer </button>

<br />

<a href="#/view2">View 2</a>

</div>

<div>

<h2>View2</h2>

City:

<br />

<input type="text" data-ng-model="city" />

<br />

<ul>

<li data-ng-repeat="cust in customers | filter:city | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city | lowercase}}</li>

</ul>

</div>

Copy after login

通过$routeProvider来配置当前页面中view1 和view2 的路由,已经每个view所对应的controller。 view1和view2会显示在当前页面标注了ng-view的位置。

同时通过config我们解耦了controller和HTML标签。 上面的例子,我们需要给html标签添加ng-controller tag来使用controller。这边直接通过config完成这样的配置。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

<!DOCTYPE html>

<html data-ng-app="demoApp">

<head>

<title>View</title>

</head>

<body>

<div>

<div data-ng-view=""></div>

</div>

<script src="angular.min.js"></script>

<script src="angular-route.min.js"></script>

<script>

var demoApp = angular.module('demoApp', ['ngRoute']);

demoApp.config(function ($routeProvider) {

$routeProvider

.when('/',

{

controller: 'SimpleController',

templateUrl: 'Partials/View1.html'

})

.when('/view2',

{

controller: 'SimpleController',

templateUrl: 'Partials/View2.html'

})

.otherwise({redirectTo:'/'});

});

var controllers = {};

controllers.SimpleController = function ($scope) {

$scope.customers = [

{ name: 'Terry Wu', city: 'Phoenix' },

{ name: 'Terry Song', city: 'NewYork' },

{ name: 'Terry Dow', city: 'NewYork' },

{ name: 'Henry Dow', city: 'NewYork' }

];

$scope.addCustomer = function () {

$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });

};

}

demoApp.controller(controllers);

</script>

</body>

</html>

Copy after login

效果如下图。

最后一个实例更接近实际工程中的用法,我们引入了Factory来初始化数据(实际工程中,在这里可访问webAPI获取数据完成初始化),Controller中则通过Factory获得数据。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

<!DOCTYPE html>

<html data-ng-app="demoApp">

<head>

<title>Using Factory</title>

</head>

<body>

<div>

<div data-ng-view=""></div>

</div>

<script src="angular.min.js"></script>

<script src="angular-route.min.js"></script>

<script>

var demoApp = angular.module('demoApp', ['ngRoute']);

demoApp.config(function ($routeProvider) {

$routeProvider

.when('/',

{

controller: 'SimpleController',

templateUrl: 'Partials/View1.html'

})

.when('/view2',

{

controller: 'SimpleController',

templateUrl: 'Partials/View2.html'

})

.otherwise({ redirectTo: '/' });

});

demoApp.factory('simpleFactory', function () {

var customers = [

{ name: 'Terry Wu', city: 'Phoenix' },

{ name: 'Terry Song', city: 'NewYork' },

{ name: 'Terry Dow', city: 'NewYork' },

{ name: 'Henry Dow', city: 'NewYork' }

];

var factory = {};

factory.getCustomers = function ()

{

return customers;

}

return factory;

});

var controllers = {};

controllers.SimpleController = function ($scope, simpleFactory) {

$scope.customers = [];

init();

function init() {

$scope.customers = simpleFactory.getCustomers();

}

$scope.addCustomer = function () {

$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });

};

}

demoApp.controller(controllers);

</script>

</body>

</html>

Copy after login

以上内容是小编给大家介绍的AngularJs 60分钟入门基础教程,希望对大家以上帮助!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles