前言
AngularJS是Google推出的一款Web應(yīng)用開(kāi)發(fā)框架。它提供了一系列兼容性良好并可擴(kuò)展的服務(wù),包括數(shù)據(jù)綁定、DOM操作、MVC和依賴注入等特性。
AngularJS核心知識(shí)點(diǎn)
- 指令(directive)和 數(shù)據(jù)綁定(Data Binding)
- 模板(Module)
- 控制器(Controller)
- 路由(Route)
- 服務(wù)(service)
- 過(guò)濾器(Filter)
指令與數(shù)據(jù)綁定
AngularJS 指令是擴(kuò)展的 HTML 屬性,帶有前綴 ng-。
常用指令:
ng-app 初始化一個(gè) AngularJS 應(yīng)用程序。
ng-init 初始化應(yīng)用程序數(shù)據(jù)。
ng-model 把元素值(比如輸入域的值)綁定到應(yīng)用程序。
ng-repeat 對(duì)于集合中(數(shù)組中)的每個(gè)項(xiàng)會(huì) 克隆一次 HTML 元素
除了 AngularJS 內(nèi)置的指令外,我們還可以創(chuàng)建自定義指令,使用 .directive 函數(shù)來(lái)添加自定義的指令。
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-init="name = '歡迎學(xué)習(xí)AngularJS'">
<p>{{name}}: <input type="text" ng-model="name"></p>
</div>
<div ng-init="quantity=1;price=5">
<h2>價(jià)格計(jì)算器</h2>
數(shù)量: <input type="number" ng-model="quantity">
價(jià)格: <input type="number" ng-model="price">
<p><b>總價(jià):</b> {{quantity * price}}</p>
</div>
<!-- ng-repeat -->
<div ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<p>循環(huán)對(duì)象:</p>
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<!-- 自定義指令 -->
<runoob-directive></runoob-directive>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<h1>我是一個(gè)自定義指令!</h1>"
};
});
</script>
</body>
</html>
模板
AngularJs的模板指的是前端模板。AngularJS有內(nèi)置的前端模板引擎,即所有頁(yè)面渲染的操作都是放在瀏覽器端來(lái)渲染的,從而減輕服務(wù)端的壓力。
AngularJs中的模板就是指帶有ng-app指令的HTML代碼。AngularJs發(fā)現(xiàn)Html頁(yè)面是否需要用AngularJs模板引擎去渲染的標(biāo)志就是ng-app標(biāo)簽。
在AngularJs中,我們寫的其實(shí)也并不是純的Html頁(yè)面,而是模板,最終用戶看到的Html頁(yè)面(也就是視圖)是通過(guò)模板渲染后的結(jié)果。
控制器
AngularJs中控制器的作用是模型和視圖之間的橋梁,而AngularJs的模型對(duì)象就是scope。所以Angularjs控制器只是scope和視圖之間的橋梁,它通過(guò)操作scope對(duì)象來(lái)改變視圖。
關(guān)于 controller 中作用域的問(wèn)題:
controller 中,如果局部 scope 和 rootScope 都存在,且有相同名字的變量,{{變量名}} 指局部變量而不是全局變量,作用域只有當(dāng)前 controller;{{root.變量名}} 是全局變量,在 ng-app="" 下任何一個(gè) controller 中都能使用。如果沒(méi)有 $scope, 只有 rootScope,那么 {{變量名}} 和 {{root.變量名}} 就沒(méi)區(qū)別了。
<div ng-app="myApp" ng-controller="cntoController">
<div><textarea ng-model="val"></textarea></div>
<div>{{val}}</div>
<div><button ng-click="click()">重置</button></div>
<br>
<!-- 控制器方法 -->
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{fullName()}}
</div>
<script>
// 創(chuàng)建模塊
var myApp = angular.module("myApp", []);
myApp.controller("cntoController", ["$scope", function ($scope) {
var defaultValue = "Learninghard 前端系列";
$scope.val = defaultValue;
$scope.click = function () {
$scope.val = defaultValue;
};
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
}
}]);
</script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
{{first}}<br>
{{$root.first}}<br>
{{second}}<br>
{{$root.second}}<br>
</div>
<div ng-controller="myCtrl2">
{{first}}<br>
{{$root.first}}<br>
{{second}}<br>
{{$root.second}}
</div>
</body>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope,$rootScope) {
$scope.first = 'ctrl局部first';
$rootScope.first = '全局first';
});
app.controller('myCtrl2', function ($scope,$rootScope) {
$scope.second = 'ctrl2局部second';
$rootScope.second = '全局second';
});
</script>
路由
AngularJS 路由允許我們通過(guò)不同的 URL 訪問(wèn)不同的內(nèi)容。
通過(guò) AngularJS 可以實(shí)現(xiàn)多視圖的單頁(yè) Web 應(yīng)用。
<body ng-app='myApp'>
<div><a href="#/list1">列表</a></div>
<br />
<div ng-view></div>
</body>
<script>
var myApp = angular.module("myApp", ['ngRoute']);
myApp.config(['$routeProvider', function($routeProvider) {
// 路由配置
var route = $routeProvider;
route.when('/list1', {
controller: 'listController',
templateUrl: 'route-list.html'
});
route.when('/view/:id', {
controller: 'viewController',
templateUrl: 'route-view.html'
});
route.when("/", {
redirectTo: '/list1'
});
route.otherwise({
redirectTo: '/list1'
});
}]);
</script>
服務(wù)
在 AngularJS 中,服務(wù)是一個(gè)函數(shù)或?qū)ο?,可在你?AngularJS 應(yīng)用中使用。
<script>
<!-- $location獲取當(dāng)前頁(yè)面的url -->
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
<!-- $http服務(wù)-->
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
<!--$timeout 服務(wù) -->
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
<!-- 自定義服務(wù) -->
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
myApp.factory("service", function() {
var list = [
{ id: 1, title: "博客園", url: "http://www.cnblogs.com" },
{ id: 2, title: "知乎", url: "http://www.zhihu.com" },
{ id: 3, title: "codeproject", url: "http://www.codeproject.com/" },
{ id: 4, title: "stackoverflow", url: "http://www.stackoverflow.com/" }
];
return function(id) {
//假如ID為無(wú)效值返回所有
if (!id) return list;
var t = 0;
angular.forEach(list, function(v, i) {
if (v.id == id) t = i;
});
return list[t];
}
});
myApp.controller("listController", ["$scope", "service", function($scope, service) {
$scope.list = service();
}]);
</script>
過(guò)濾器
過(guò)濾器可用于轉(zhuǎn)換數(shù)據(jù),常用過(guò)濾器:
uppercase 格式化字符串為大寫。
lowercase 格式化字符串為小寫。
currency 格式化數(shù)字為貨幣格式。
currency 格式化數(shù)字為貨幣格式。
orderBy 根據(jù)某個(gè)表達(dá)式排列數(shù)組。
filter 從數(shù)組項(xiàng)中選擇一個(gè)子集。
自定義過(guò)濾器
<p>姓名為 {{ lastName | uppercase }}</p>
<p>姓名為 {{ lastName | lowercase }}</p>
數(shù)量: <input type="number" ng-model="quantity">
價(jià)格: <input type="number" ng-model="price">
<p>總價(jià) = {{ (quantity * price) | currency }}</p>
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
<p>輸入過(guò)濾:</p>
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
<div ng-app="myApp" ng-controller="myCtrl">
姓名: {{ msg | reverse }}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.msg = "Runoob";
});
app.filter('reverse', function() { //可以注入依賴
return function(text) {
return text.split("").reverse().join("");
}
});
</script>