search
HomeWeb Front-endJS TutorialAngularJs 60-minute basic tutorial for getting started_AngularJS

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.

<!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>

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

<!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>

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.

<!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 id="Looping-with-the-ng-repeat-Directive">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>

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 |.

<!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>

运行的结果:


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。

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

<!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>

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

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

<div>
<h2 id="View">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 id="View">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>

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

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

<!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>

效果如下图。

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

<!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>

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

Statement
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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 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.

See all articles

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor