AngularJS 教程
AngularJS教程
AngularJS 是一款用于构建 Web 应用的 JavaScript 框架。它提供了一系列的工具和指令,用于快速开发单页应用 (SPA)。
1. AngularJS基础
1.1 指令
AngularJS 中的指令是一种特殊的 HTML 属性,用于改变 HTML 元素的行为。AngularJS 提供了很多内置的指令,例如 ng-app、ng-controller、ng-model、ng-show 等,开发者也可以自定义指令来扩展其功能。
1.2 模板语法
AngularJS 使用了一种类似于 HTML 的模板语法,用于将应用逻辑与视图绑定在一起。其中,{{}} 表示插值表达式,用于将数据插入到页面中,ng-repeat 指令可以用于循环渲染元素。
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{ message }}</p>
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>
// 定义模块
var app = angular.module("myApp", []);
// 定义控制器
app.controller("myCtrl", function($scope) {
$scope.message = "Hello, World!";
$scope.items = ["item1", "item2", "item3"];
});
1.3 双向数据绑定
AngularJS 通过双向数据绑定机制,使得数据和视图保持同步。当视图中的数据发生变化时,数据模型也会跟着变化。反之亦然。ng-model 指令可以用来实现双向数据绑定。
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name">
<p>Hello, {{ name }}</p>
</div>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.name = "AngularJS";
});
2. AngularJS进阶
2.1 服务(Service)
在 AngularJS 中,服务是用来组织和共享代码的一种单例对象。AngularJS 内置了很多服务,例如 $http、$location、$timeout、$q 等。
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$http.get("/api/users").then(function(response) {
$scope.users = response.data;
});
});
2.2 路由(Router)
AngularJS 内置了一个路由器,可以用于实现单页应用。通过路由器,我们可以将 URL 和视图绑定在一起,并且可以控制视图的渲染。
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "HomeController"
})
.when("/about", {
templateUrl: "about.html",
controller: "AboutController"
})
.otherwise({
redirectTo: "/"
});
});
app.controller("HomeController", function($scope) {
$scope.message = "Welcome to My Website!";
});
app.controller("AboutController", function($scope) {
$scope.message = "About Me";
});
2.3 依赖注入(DI)
AngularJS 通过依赖注入机制,来实现对象之间的解耦和代码复用。在 AngularJS 中,我们可以使用 $injector 服务来获取并使用其他对象,例如控制器、服务等。
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http, $timeout) {
$timeout(function() {
$http.get("/api/users").then(function(response) {
$scope.users = response.data;
});
}, 1000);
});
app.factory("userService", function($http) {
return {
getUsers: function() {
return $http.get("/api/users");
},
addUser: function(user) {
return $http.post("/api/users", user);
}
};
});
app.controller("myCtrl2", function($scope, userService) {
userService.getUsers().then(function(response) {
$scope.users = response.data;
});
});
总结
AngularJS 是一个功能强大、易于使用、文档丰富、社区活跃的 JavaScript 框架。本文仅对其进行了简要的介绍,有关更多详细信息,请参阅其官方文档。