AngularJS 参考手册

AngularJS 是一个强大的 JavaScript 框架,帮助开发者构建动态单页面应用程序(SPA)。以下是一些 AngularJS 中最常用的核心功能、指令、服务和概念的参考手册。


1. 模块 (Module)

AngularJS 应用通过模块来组织代码。一个模块是一个容器,用于组织不同的部分(如控制器、服务、过滤器等)。

创建模块

var app = angular.module('myApp', []);

模块的依赖注入

var app = angular.module('myApp', ['ngRoute', 'ngAnimate']);


2. 控制器 (Controller)

控制器是 AngularJS 的核心,它们用来控制应用的行为和数据。控制器管理作用域($scope)和视图的交互。

创建控制器

app.controller('MainController', function($scope) {
    $scope.message = 'Hello, AngularJS!';
});

控制器作用域

  • $scope:控制器和视图之间的数据绑定对象。
  • $scope 作用域的变量可以直接在 HTML 中绑定并更新
<h1>{{ message }}</h1>


3. 数据绑定 (Data Binding)

AngularJS 提供了双向数据绑定,使得视图和数据模型保持同步。

双向数据绑定

<input type="text" ng-model="name">
<p>Hello, {{ name }}!</p>

  • ng-model:用于创建表单元素与数据模型的绑定。
  • {{ name }}:表达式在视图中显示数据模型的值。

4. 指令 (Directives)

指令是 AngularJS 的核心部分,用来扩展 HTML,提供更多的功能。

常用指令

  • ng-app:定义 AngularJS 应用的范围。
  • ng-controller:定义控制器。
  • ng-repeat:重复元素,通常用于渲染列表。
<div ng-app="myApp" ng-controller="MainController">
    <ul>
        <li ng-repeat="item in items">{{ item }}</li>
    </ul>
</div>

自定义指令

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        template: '<h1>{{ message }}</h1>',
        link: function(scope, element, attrs) {
            scope.message = "This is a custom directive!";
        }
    };
});


5. 过滤器 (Filters)

过滤器用于格式化数据或转换数据。AngularJS 内置了许多常用的过滤器,如 currencydateuppercase 等。

使用内置过滤器

<p>{{ amount | currency }}</p>
<p>{{ birthday | date:'yyyy-MM-dd' }}</p>

自定义过滤器

app.filter('reverse', function() {
    return function(input) {
        return input.split('').reverse().join('');
    };
});


6. 服务 (Services)

服务是 AngularJS 中用于存放应用逻辑、共享数据和功能的对象。服务通过依赖注入来共享数据。

使用服务

app.service('myService', function() {
    this.sayHello = function() {
        return 'Hello from Service!';
    };
});

app.controller('MainController', function($scope, myService) {
    $scope.message = myService.sayHello();
});

内置服务

  • $http:用于发送 HTTP 请求。
  • $timeout:用于延迟执行代码。
  • $location:用于获取和修改浏览器的 URL。

7. 路由 (ngRoute)

AngularJS 提供了 ngRoute 模块来处理应用的路由。通过路由,可以根据 URL 动态切换不同的视图和控制器。

配置路由

app.config(function($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'home.html',
            controller: 'HomeController'
        })
        .when('/about', {
            templateUrl: 'about.html',
            controller: 'AboutController'
        })
        .otherwise({
            redirectTo: '/home'
        });
});

HTML 中使用 ng-view

<div ng-view></div>


8. 动画 (ngAnimate)

AngularJS 提供了内置的 ngAnimate 模块,用于实现元素的动画效果。

动画的应用

<div ng-app="myApp" ng-controller="MainController">
    <button ng-click="toggle()">Toggle Animation</button>
    <div ng-show="showElement" class="animate-box">Animated Box</div>
</div>

<script>
app.controller('MainController', function($scope) {
    $scope.showElement = true;
    $scope.toggle = function() {
        $scope.showElement = !$scope.showElement;
    };
});
</script>

<style>
.animate-box {
    width: 200px;
    height: 200px;
    background-color: #4CAF50;
    margin-top: 20px;
    opacity: 1;
    transition: opacity 0.5s ease;
}

.ng-hide {
    opacity: 0;
}
</style>

常用动画指令

  • ng-show:在元素显示时应用动画。
  • ng-hide:在元素隐藏时应用动画。

9. HTTP 服务 (AJAX)

AngularJS 提供了 $http 服务,允许你发送 AJAX 请求和处理响应。

使用 $http 发送 GET 请求

app.controller('MainController', function($scope, $http) {
    $http.get('https://jsonplaceholder.typicode.com/posts')
        .then(function(response) {
            $scope.posts = response.data;
        });
});

使用 $http 发送 POST 请求

app.controller('MainController', function($scope, $http) {
    var data = { title: 'New Post', body: 'This is a new post.' };
    $http.post('https://jsonplaceholder.typicode.com/posts', data)
        .then(function(response) {
            $scope.message = 'Post created!';
        });
});


10. 表单验证 (Form Validation)

AngularJS 提供了内置的表单验证功能,可以在客户端验证表单输入。

表单验证

<form name="myForm" ng-submit="submitForm()">
    <input type="text" name="username" ng-model="username" required>
    <span ng-show="myForm.username.$error.required">用户名是必填的!</span>
    
    <button type="submit" ng-disabled="myForm.$invalid">提交</button>
</form>

常用验证属性

  • required:字段必填。
  • ng-minlengthng-maxlength:设置字符长度范围。
  • ng-pattern:验证输入的正则表达式。

11. 依赖注入 (Dependency Injection)

AngularJS 使用依赖注入(DI)来将服务、控制器、指令等依赖项注入到组件中,简化了应用的模块化和可测试性。

基本依赖注入

app.controller('MainController', function($scope, $http) {
    $scope.message = 'Welcome to AngularJS!';
});

AngularJS 会自动注入 $scope$http 服务。


结语

AngularJS 提供了许多有用的功能和工具,帮助开发者快速构建高效、动态的单页面应用。掌握 AngularJS 的核心概念,如模块、控制器、指令、数据绑定等,能够使你更好地组织和管理代码,提升应用的可维护性和扩展性。

更多详细的 AngularJS 文档和参考资料可以访问 AngularJS 官方文档