Home  >  Article  >  Web Front-end  >  How to use angularjs? Detailed analysis of angularjs framework examples (with complete examples)

How to use angularjs? Detailed analysis of angularjs framework examples (with complete examples)

寻∝梦
寻∝梦Original
2018-09-08 11:48:112064browse

This article introduces a summary of the framework knowledge points of angularjs, with complete examples and detailed explanations of complete tags. Next, let us read this article together

1. What is AngularJS?

It is a front-end framework developed by Google with an MVC structure. In the Angular application, the view layer is DOM, and the controller is JavaScript Class, model data is stored in object properties.

2. Data Binding

By declaring a certain part of the interface to be mapped to properties of JavaScript , let them automatically Synchronization, this programming method is data binding. There is no need to register a listener for the field, and the object properties and interface display can be changed synchronously.

3. Dependency Injection

No need to re-create the object, you will need to use the object $scope or $loaction is injected into the constructor in the following way. This is dependency injection.

function HelloController($scope, $location) {
$scope.greeting = { text: 'Hello' };
// use $location for something good here...
}

4. Directives

The core layer of the framework has a powerful DOM transformation engine that allows you to extend HTML Syntax. The ng-controller in HTML is used to specify which controller to serve which view, ng- modelBind an input box to the model part. We call these HTML extension instructions.

5. Explain each tag based on examples

<!DOCTYPE html>
<html  ng-app>
<head>
<base/>
<title>Your Shopping Cart</title>
<script src="../frm/angular/angular.js"></script>
</head>
<body ng-controller=&#39;CartController&#39;>
<h1>Your Order</h1>
<p ng-repeat=&#39;item in items&#39;>
<span>{{item.title}}</span>
<input ng-model=&#39;item.quantity&#39;/>
<span>{{item.price | currency}}</span>
<span>{{item.price * item.quantity | currency}}</span>
<button ng-click="remove($index)"> Remove </button>
</p>
<script>
function CartController($scope) {
////@formatter:off
$scope.items = [{
title : &#39;Paint pots&#39;,
quantity : 8,
price : 3.95
}, {
title : &#39;Polka dots&#39;,
quantity : 17,
price : 12.95
}, {
Title : &#39;Pebbles&#39;,
quantity : 5,
price : 6.95
}];
////@formatter:on
$scope.remove = function(index) {
$scope.items.splice(index, 1);
};
}
</script>
</body>
</html>

According to the above code, An explanation of the key content:

1)

ng-app Properties tell Angular which part of the page it should manage. Since we put it on the html element, it tells Angular to manage the entire page. If you are integrating Angular with an existing application that uses other methods to manage pages, then you may need to place p## in the application #superior.

2

at Angular # In ##, the page area managed by the JavaScript class is called a controller. By including a controller in the body tag, the declared CartController will manage body# Anything between ## tags. 3

ng-repeat represents itemscopy each element in the array once to in this p DOM. In each copy of p, an attribute called item is also set to represent the current element, so we can use. As you can see, each p contains the product name, quantity, unit price, total price and a remove button.

4) {{item.title}}

As demonstrated The 'Hello World' example, data binding is to insert the value of the variable into a certain part of the page through {{ }} Stay in sync. The complete expression {{item.title}} retrieves the current item in the iteration and then adds the current item's titile attribute value Insert into DOM.

5

ng-model Definition Created a data binding between the input field and item.quantity. span{{ in the tag }}A one-way relationship is established and the value is inserted here. But the application needs to know that when the user changes the quantity, it can change the total price, which is what we want. By using ng-model we will keep changes in sync with our model. ng-modelStates that the value of item.quantity will be inserted into the input box. Whenever the user enters a new value, it will automatically Update item.quantity.

6 {{item.price | currency}}

We want the unit price to be formatted in USD. Angular has a feature called a filter that allows us to convert text. There is a filter called currency that will do this dollar format formatting for us. .

7

     Click this button to call the remove() function. Also passed is $index, which contains the iteration order of ng-repeat so that we know which item to remove.

8function CartController($scope) {

CartController Manage the logic of this shopping cart. Through this we tell Angular that the controller

needs an object called $scope . $scope is used to bind data to elements on the interface.

9$scope.remove = function(index) {

$scope.items.splice(index, 1);

};

我们希望 remove()函数能够绑定到界面上,因此我们也把它增加到$scope中。对于这

个内存中的购物车版本,remove()函数只是从数组中删除了它们。因为通过ng-repeat创建

的这些

是数据捆绑的,当某项消失时,列表自动收缩。记住,无论何时用户点击移除

按钮中的一个,都将从界面上调用 remove()函数。(想看更多就到PHP中文网AngularJS开发手册中学习)

 6. 调用 Angular

任何应用使用 Angular 必须做两件事:

1)加载 angular.js

2)使用 ng-app告知Angular管理哪一部分的DOM

7. 加载脚本

很简单:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>

推荐使用 Google CDNGoogle的服务器是非常快的,脚本是跨应用缓存的。那就是说,如果你的用户有多个使用Angular的应用,它只下载一次。同样,如果用户访问过使用Google AngularCDN链接,那么当他访问你的站点时没有必要再次下载。

8. 模块

<html ng-app=&#39;myApp&#39;>
<body ng-controller=&#39;TextController&#39;>
<p>{{someText.message}}</p>
<script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script>
var myAppModule = angular.module(&#39;myApp&#39;, []);
myAppModule.controller(&#39;TextController&#39;,
function($scope) {
var someText = {};
someText.message = &#39;You have started your journey.&#39;;
$scope.someText = someText;
});
</script>
</body>
</html>

在这个模板中,我们告知 ng-app 元素我们的模块名,myApp。然后我们调用了Angular对象创建一个名为myApp的模块,传递了控制器函数给模块的控制器函数。

只要记住,远离全局命名空间是一件好事。模块化这是我们通用的机制。

9.  模板和数据绑定

Angular 应用中的模板只是那些我们从服务器加载的 HTML文档或者是定义在<script></script>标签中的一些静态资源。你在模板中定义界面,在界面组件中使用标准的HTML加上Angular标识符。

基本的启动流程就像这样:

1)用户请求应用的第一页面。

2) The user's browser sends a HTTP link to your server and loads the index.html## containing the template. #page.

3

)Angular loads to the page, waits for the page to fully load, then looks for ng-appDefine the boundaries of the template.

4

)AngularFind identifiers and bundles through templates. The result is that the listener and the DOM operation are registered, and the initialization data is queried from the server. The final result of this work is that the application has been bootstrapped (startup completed, computer terminology), converting the template into a view just like DOM.

5

) You connect to the server and load additional data on demand that you need to display to the user.

By structuring your application using Angular , your application's templates and the data that populates them are separated. The benefit of this is that these templates are now cacheable. After the first load, only new data is loaded to the browser. Only JavaScript, images, CSS and other resources, caching these templates can give the application better performance.

10.

ng-bind Identifier display and update text

ng-bind

and {{}} and other two methods are equivalent in displaying text. The difference is that the user cannot see the content until the data is loaded. 11. src Suggestions for and

href

attributesWhen data is bound to an How to use angularjs? Detailed analysis of angularjs framework examples (with complete examples) or

tag, in src## Paths using {{}} in #or href cannot run properly. However, you should use the ng-src attribute, similar to the

tag, You should use ng-href12. $route service Route

can be pointed to for a given browse

URL

Detailed specification

AngularBe able to load and display a template, instantiate a controller to provide context for the template. When

URL

is /Find/activityDetail

,

Angular will The loading template address is: Find/views/activityDetail.html. otherwise() Tell the route to go to this section if there is no match.

13. 用指令修改DOM

var  appModule  =  angular . module ( &#39;app&#39; , []);
appModule . directive ( &#39;ngbkFocus&#39; , function () {
return {
link : function ( scope , element , attrs , controller)  {
element [ 0 ]. focus ();
}
};
});

14. 校验用户输入

模板代码:

<h1> Sign Up </h1>
<form  name=&#39;addUserForm&#39; ng-controller= "AddUserController" >
<p ng-show=&#39;message&#39;>{{message}}</p>
<p> First  name: <input  name= &#39;firstName&#39; ng-model= &#39;user.first&#39; required ></p>
<p>Last name: <input  ng-model=&#39;user.last&#39;  required ></p>
<p>Email: <input  type=&#39;email&#39; ng-model=&#39;user.email&#39;  required ></p>
<p>Age: <input type= &#39;number&#39;
ng-model= &#39;user.age&#39;  ng-maxlength= &#39;3&#39;
ng-min= &#39;1&#39; ></p>
<p><button  ng-click=&#39;addUser()&#39;
ng-disabled= &#39;!addUserForm.$valid&#39; > Submit </button>
< /ng-form>

控制器:

function AddUserController ( $scope ) {
$scope . message =  &#39;&#39; ;
$scope . addUser = function  () {
//  TODO for  the reader: actually  save user to database...
$scope . message = &#39;Thanks, &#39;  +  $scope . user . first +  &#39;,  we added  you!&#39; ;
};
}

说明:

使用了来自 HTML5 required属性,email类型、number类型的输入

框,在一些字段上做我们的校验。

在控制器内部,可以通过$valid 属性来访问表单的校验状态。当表单中所有的请求都是合法时,Angular 会把它设置成 true。我们可以使用$valid属性来做额外的事,比如当表单还未完成时禁用提交按钮。

通过个体提交按钮添加 ng-disbaled,能够阻止非法状态的提交。

15. ‘use strict’是什么意思

“use strict”是一个指令,指示解释器用更严格的方式检查代码。"use strict"开启严格模式以后,一些js糟糕的特性都会被禁用,比如不能用with,也不能在意外的情况下给全局变量赋值。严格模式下的eval函数的行为和非严格模式的也不相同。

16. factory,service,provider自定义服务,services.js

 How to use angularjs? Detailed analysis of angularjs framework examples (with complete examples)

1)  Factory 就是创建一个对象,为它添加属性,然后把这个对象返回出来。你把 service传进controller之后,在controller里这个对象里的属性就可以通过factory使用了。

2) Service 是用"new"关键字实例化的。因此,你应该给"this"添加属性,然后service返回"this"。你把service传进controller之后,在controller"this"上的属性就可以通过service来使用了。

3) Providers is the only service# that you can pass into the .config() function ##. When you want to perform module-wide configuration before the service object is enabled, you should use provider.

Okay, this article ends here (if you want to see more, go to the PHP Chinese website AngularJS User Manual to learn). If you have any questions, you can Leave a question below.

The above is the detailed content of How to use angularjs? Detailed analysis of angularjs framework examples (with complete examples). For more information, please follow other related articles on the PHP Chinese website!

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