search
HomeWeb Front-endHTML TutorialAngular 基础入门_html/css_WEB-ITnose

简介

什么是AngularJS

  • 一个功能非常完备的前端框架,通过增强HTML的方式提供一种便捷开发Web应用程序的方式
  • 其核心特点就是几乎无任何DOM操作,让开发人员的精力和时间全部集中于业务
  • MVC的特性增强了代码的结构和可维护性,应对需求的变化做出最小的改动

为什么使用AngularJS

  • 更少的代码实现更强劲的功能
  • 提供了很多在传统后端开发中大量使用的思想和方式,提高前台代码的结构和可维护性

使用AnuglarJS的流程

  1. 在HTML中引入Angular.js文件
  2. 在自己的代码中定义一个AngularJS的模块
  3. 将模块作用到HTML中的某个节点
  4. 根据模块的功能定义控制器
  5. 根据当前页面原型设计$scope的结构
  6. 通过$scope暴露数据和行为
  7. 将暴露出来的数据和行为通过特定的指令绑定到HTML节点中

MVC

  • 一种应用程序的设计思想,其目的是为了对应用程序的组成进行划分,让结构更加清晰可维护性更高,确保每个原件都有明确的单一职责

模块

  • 可以通过 angular.module() 方法操作模块
  • 注意:该方法只有在传入两个参数时才会创建模块,否则为获取已有模块

定义模块

// 第一个参数为模块名,第二个参数为当前这个模块所依赖的模块列表angular.module('ModuleName', []);  

获取已经定义过的模块

var existModule = angular.module('ExistModule');  

如何划分模块

1.根据当前需要开发的应用程序的组成划分需要多少模块,

比如: - 注册模块 - 登录模块 - 用户列表页模块 - 用户详细页模块 - etc.

2. 根据文件类型的不同来划分

比如: - 所有的控制器 - 所有的服务 - 所有的指令 - etc.

控制器

当下的企业开发,如果使用Angular,主要就是开发对应的控制器和模型

定义控制器

定义控制器可以有三种方式,注意第一种已经被淘汰

传统方式(不要再用了)

在最早期的 Angular 代码中可能会见到以全局函数的方式定义的控制器:

<!DOCTYPE html>  <html lang="en">  <head>    <meta charset="UTF-8">  <title>早期的控制器定义方式-全局函数</title></head>  <body ng-app>    <div ng-controller="FooController">    <input type="button" value="clicked me!" ng-click="say()">  </div></body>  </html>  
function FooController($scope) {    $scope.say = function(){    console.log('hello angular');  };}

这种方式现在已经不被支持,就算没有淘汰也不应该使用,太low(全局作用域的问题)

常用方式(挂载在某个模块下)(必须掌握)

Angular中最常见的一种使用方式,通过模块中定义的 controller 方法定义控制器

<!DOCTYPE html>  <html lang="en">  <head>    <meta charset="UTF-8">  <title>常用方式(挂载在某个模块下)</title></head>  <body ng-app="MyModule">    <div ng-controller="FooController">    <input type="button" value="clicked me!" ng-click="say()">  </div></body>  </html>  
angular.module('MyModule', [])    .controller('FooController', function($scope) {    $scope.say = function(){      console.log('hello angular');    };  });

定义类型的方式(构造函数)

对于喜欢通过定义构造函数的方式编写面向对象代码的同学可以使用构造函数的形式定义一个控制器

<!DOCTYPE html>  <html lang="en">  <head>    <meta charset="UTF-8">  <title>面向对象的方式</title></head>  <body ng-app="MyModule">    <div ng-controller="FooController as context">    <input type="button" value="clicked me!" ng-click="context.say()">  </div></body>  </html>  
function FooController() {    this.message = 'hello angular';}FooController.prototype.say = function() {    console.log(this.message);};angular.module('MyModule', [])    .controller('FooController', FooController);

注意事项

  • 在以上的使用方式中,如果需要为控制器函数注入类似 $scope 之类的参数,必须确保参数名为一个特定值
  • 也就是说Angular会根据参数名称自动注入对应的对象(与参数个数,出现顺序无关),所以参数名一定不能写错
  • 但是,我们对于写完的JS代码经常会在上线之前对代码进行压缩
  • 压缩的过程中如果启用混淆压缩的话,就会造成参数名变化
  • 一旦变化了参数名,NG就无法为其注入对应的对象了
  • 所以,最安全的写法就是不要依赖参数名(依赖不会变化的东西):
angular.module('MyModule', [])    .controller('FooController', ['$scope', function(whatever) {    whatever.say = function(){      console.log('hello angular');    };  }]);

解决方式就是将创建控制器的第二个参数改为一个数组,数组的最后一个成员就是以前的控制器函数,前面的成员就是控制器函数需要注入的对象列表,按照顺序对应

扩展小知识:实现原理

如何根据参数名传入特定对象?

function getFnParams(fn) {    if (typeof fn == 'function') {    var mathes = /.+\((.+)\)/.exec(Function.prototype.toString.call(fn));    if (mathes[1]) {      var args = mathes[1].replace(/\s/g, '').split(',');      return args;    }  }}function foo(id, name, a1ge) {}console.log(getFnParams(foo));  

$scope

  • 视图和控制器之间的数据桥梁
  • 用于在视图和控制器之间传递数据
  • 用来暴露数据模型(数据,行为)

ViewModel

  • $scope 实际上就是MVVM中所谓的VM(视图模型)
  • 正是因为$scope在Angular中大量使用甚至盖过了C(控制器)的概念,所以很多人(包括我)把Angular称之为MVVM框架
  • 这一点倒是无所谓,具体看怎么用罢了

大家必须掌握的就是如何根据一个原型抽象出对应的视图模型

表达式

类似于模版引擎的语法

作用:

使用表达式把数据绑定到 HTML。

语法:

  • 表达式写在双大括号内:{{ expression }}。
  • AngularJS 表达式很像 JavaScript 表达式
  • 它们可以包含文字、运算符和变量
  • 如 {{ 5 + 5 }} 或 {{ firstName + '-' + lastName }}

支持的类型

  • 数字 {{ 100 + 100 }}
  • 字符串 {{ 'hello' + 'angular' }}
  • 对象 {{ zhangsan.name }}
  • 数组 {{ students[10] }}

与JS的比较:

相同点: - AngularJS 表达式可以包含字母,操作符,变量。

不同点: - AngularJS 表达式可以写在 HTML 中。 - AngularJS 表达式不支持条件判断,循环及异常。 - AngularJS 表达式支持过滤器。

指令

  • 在 AngularJS 中将前缀为 ng- 这种属性称之为指令,其作用就是为 DOM 元素调用方法、定义行为绑定数据等
  • 简单说:当一个 Angular 应用启动,Angular 就会遍历 DOM 树来解析 HTML,根据指令不同,完成不同操作

指令标准属性的问题

  • ng-xxx 的属性本身并不是标准中定义的属性
  • 很多情况下语法校验是无法通过的
  • HTML5 允许扩展的(自制的)属性,以 data- 开头。
  • 在 AngularJS 中可以使用 data-ng- 来让网页对 HTML5 有效。
  • 二者效果相同。

内置指令

ng-app

  • ng-app 指令用来标明一个 AngularJS 应用程序
  • 标记在一个 AngularJS 的作用范围的根对象上
  • 系统执行时会自动的执行根对象范围内的其他指令
  • 可以在同一个页面创建多个 ng-app 节点(不推荐)
  • 创建多个ng-app时,默认只能执行第一个,后面的需要手动引导:angular.bootstrap()
  • 标记的范围尽可能小,性能

ng-model

  • 用于建立界面上的元素到数据模型属性的双向数据绑定
  • 一般情况绑定到元素的value属性上
  • 但是在checkbox之类的表单元素会有不同

ng-bind

ng-bind-html

ng-repeat

ng-class

ng-cloak

ng-show/ng-hide/ng-if

ng-src

ng-switch

其他常用指令

  • ng-checked:
    • 单选/复选是否选中,只是单向绑定数据
  • ng-selected:
    • 是否选中,只是单向绑定数据
  • ng-disabled:
    • 是否禁用
  • ng-readonly:
    • 是否只读

常用事件指令

不同于以上的功能性指令,Angular还定义了一些用于和事件绑定的指令:

  • ng-blur:
    • 失去焦点
  • ng-change:
    • 发生改变
  • ng-copy:
    • 拷贝完成
  • ng-click:
    • 单击
  • ng-dblclick:
    • 双击
  • ng-focus:
    • 得到焦点
  • ng-blur:
    • 失去焦点
  • ng-submit:
    • 表单提交

自定义指令

  • 指令无外乎增强了 HTML,提供额外的功能
  • 以上的指令基本上已经可以满足我们的绝大多数需要了
  • 少数情况下我们有一些特殊的需要,可以通过自定义指令的方式实现:

组件式指令Demo

myModule.directive('hello', function() {    return {    restrict: 'E',    template: '<h1 id="Hello-world">Hello world</h1>',    replace: true  };});

功能型指令Demo

myApp.directive("ngHover", function() {    return function(scope, element, attrs) {    element.bind("mouseenter", function() {      element.css("background", "yellow");    });    element.bind("mouseleave", function() {      element.css("background", "none");    });  }});

自定义指令的类型

  1. E:Element(元素)
  2. A:Attribute(属性)
  3. C:Class(类名)
  4. M:Comment(注释)

注意:

在定义指令应该使用驼峰命名法,使用指令时应该使用的是全小写字母中划线分割的方式

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
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

How to efficiently add stroke effects to PNG images on web pages?How to efficiently add stroke effects to PNG images on web pages?Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

What is the purpose of the <datalist> element?What is the purpose of the <datalist> element?Mar 21, 2025 pm 12:33 PM

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <progress> element?What is the purpose of the <progress> element?Mar 21, 2025 pm 12:34 PM

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <meter> element?What is the purpose of the <meter> element?Mar 21, 2025 pm 12:35 PM

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools