Angular JS 學習筆記
一、Angular JS 常用指令
ng-app=””
- 專案中不能為空,定義一個Angular JS 應用程式,指定了它的使用範圍,一個頁面只能有一個ng-app,如果有多個,則第一個有效。ng-app可以出現在html文件的任意一個元素上。
ng-init=”變數=’值’;變數=’值’”
- 初始化變數的值,有多個變數時,中間用分號隔開。
ng-disabled=”布林值”
- true,禁用;false,可用
- ng-show=”布林值”
- true,顯示;false,隱藏
ng-hide=”布林值”
true,隱藏;false,顯示
- ng-submit=”方法名(引數)”
- 提交
ng-switch=”變數”
- 類似於switch-case
示例:
- 類似於switch-case
<div ng-switch="myVar">
<div ng-switch-when="dogs">
<h1>Dogs</h1>
<p>Welcome to a world of dogs.</p>
</div>
<div ng-switch-when="tuts">
<h1>Tutorials</h1>
<p>Learn from examples.</p>
</div>
<div ng-switch-when="cars">
<h1>Cars</h1>
<p>Read about cars.</p>
</div>
</div>
- ng-if=
"$odd"
//表格,$odd,奇數行;$even,偶數行;$index,表格序號
示例:
<table>
<tr style="{{$even?'background-color: #f1f1f1':''}}" ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
- ng-model=”變數”
- 定義變數名,一個頁面中可以有多個。將元素值(比如輸入域的值)繫結到應用程式。合法),
$dirty(值改變),$touched(是否通過觸屏點選),$error(驗證使用者輸入),$valid(欄位內容合法),$invalid(欄位內容非法)
示例:
- 定義變數名,一個頁面中可以有多個。將元素值(比如輸入域的值)繫結到應用程式。合法),
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">
Email:
<input type="email" name="myAddress" ng-model="myText" required>
<p>編輯郵箱地址,檢視狀態的改變。</p>
<h1>狀態</h1>
<p>Valid: {{myForm.myAddress.$valid}} (如果輸入的值是合法的則為 true)。</p>
<p>Dirty: {{myForm.myAddress.$dirty}} (如果值改變則為 true)。</p>
<p>Touched: {{myForm.myAddress.$touched}} (如果通過觸屏點選則為 true)。</p>
<p>Error: {{myForm.myAddress.$error.email}}(不是一個合法的郵箱地址則為true)</p>
</form>
</body>
</html>
- ng-bind=”變數”
- 繫結變數名,獲取該變數的資料。這裡的變數就是ng-model的變數名。但是一般都用雙重花括號來獲取變數的值,比如:{{變數}}與HTML屬性ng-bind=”變數”效果一樣。將應用程式檢視繫結到html檢視。
- 當ng-bind和{{}}同時使用時,ng-bind繫結的值覆蓋該元素的內容。
示例:
<div ng-app="" ng-init="firstName='John'">
//<p>姓名為 <span>{{firstName}}</span></p>
<p>姓名為 <span ng-bind="firstName"></span></p>
ng-directives,自定義指令
- 使用.directive函式來新增自定義的指令,自定義的指令可以通過元素名、屬性、類名、註釋 四種方式來呼叫指令。示例:
(1)<runoob-directive></runoob-directive> (2)<div runoob-directive></div> (3)<div class="runoob-directive"></div> (4)<!-- directive:runoob-directive -->
- 使用.directive函式來新增自定義的指令,自定義的指令可以通過元素名、屬性、類名、註釋 四種方式來呼叫指令。示例:
ng-options
- 使用ng-options建立選擇框,
示例:
- 使用ng-options建立選擇框,
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-init="selectedName = names[0]" ng-model="selectedName" ng-options="x for x in names">
<!-- ng-options選擇的是物件,可以獲取更多的資訊 -->
</select>
<select>
<option ng-repeat="x in names">{{x}}</option>
<!-- ng-repeat選擇的是字串 -->
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Google", "Runoob", "Taobao"];
});
</script>
- ng-repeat
- 使用ng-repeat重複HTML元素
示例:
- 使用ng-repeat重複HTML元素
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<p>迴圈物件:</p>
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
ng-controller
- 定義了控制器。一個ng-app中可以有多個ng-controller。如果把ng-app比做一層樓,例如ng-app=”3F”,則 ng-controller相當於ng-controller=”3F-0001”,ng-controller=”3F-0002”。(在大型的應用程式中,通常把控制器儲存在外部檔案中。)
- 引數 :
$scope
,作用域,類似於區域性作用域,一個controller對應一個$scope - 引數:
$rootScope
,根作用域,類似於全域性變數,在一個ng-app類有效,存在多個rootScope時,最後一個 rootScope有效。 - 引數:
$location
,對應window.location,可以返回當前頁面的URL地址。 - 引數:
$http
,用於讀取web伺服器上資料的服務。 - 引數:
$timeout(function(){}(函式),2000(時間))
,延遲,兩秒後顯示資訊。可用於設定單次或多次延時服務。 - 引數:
$interval(function(){}(函式),1000(時間))
,計時器,每一秒顯示資訊。可用於設定始終執行的延時服務。 - 服務:
$watch,$scope.$watch('firstName',function(){})//監聽firstName的變化,更新fullName
,監聽器。 - 服務:
$apply,$scope.$apply(function(){});setInterval($scope.setTime,1000);//$apply 方法可以修改資料
自定義引數(服務):
app.service('hexafy',function(){this.myFunc = function(x){return x.toString(16);}}); app.controller('myCtrl',function($scope,hexafy){$scope.hex = hexafy.myFunc(255);})
示例:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<p>嘗試修改以下表單。</p>
<div ng-controller="myCtrl">
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{firstName + " " + lastName}}
</div>
<div ng-controller="myCtrl2">
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.firstName="Tome";
$scope.lastName="Li";
});
app.controller('myCtrl2',function($scope){
$scope.firstName="Ming";
$scope.lastName="Li";
});
//$http用法1
app.controller('myCtrl', function($scope, $http) {
$http({
method: 'GET',
url: 'https://www.runoob.com/try/angularjs/data/sites.php'
}).then(function successCallback(response) {
$scope.names = response.data.sites;
}, function errorCallback(response) {
// 請求失敗執行程式碼
});
});
//$http 用法2
//$http.get('/someUrl', config).then(successCallback, errorCallback);
//$http.post('/someUrl', data, config).then(successCallback, errorCallback);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://www.runoob.com/try/angularjs/data/sites.php")
.then(function (response) {$scope.names = response.data.sites;});
});
</script>
</body>
</html>
ng-show
- 顯示,true,隱藏,false
ng-click
- 點選事件
ng-include
- 包含HTML檔案和AngularJS程式碼。
- 跨域包含需要設定域名訪問白名單。
ng-class
- ng-view
- 檢視
- ng-enter
- ng-leave
示例:
<body ng-app="myApp">
<div ng-include="'http://c.runoob.com/runoobtest/angular_include.php'"></div>
<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([//跨域設定白名單
'http://c.runoob.com/runoobtest/**'
]);
});
</script>
</body>
二、Angular JS 使用方式
指令: ng-app,ng-model等以ng開頭的HTML屬性
表示式:{{expression}}
示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="">
<p>名字 : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
過濾器:
- 使用方式:將一個管道字元(|)和一個過濾器新增到表示式中。
- 過濾器的型別有currency(格式化數字為貨幣格式)、filter(過濾,相當於查詢)、lowercase、orderBy、uppercase。
- 示例
<div ng-app="myApp" ng-controller="namesCtrl">
<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>
舉例:
1、大小寫轉換
{{ "lower cap string" | uppercase }} // 結果:LOWER CAP STRING
{{ "TANK is GOOD" | lowercase }} // 結果:tank is good
2、date格式化
{{1490161945000 | date:"yyyy-MM-dd HH:mm:ss"}} // 2017-03-22 13:52:25
3、number 格式化(保留小數)
{{149016.1945000 | number:2}}
4、currency貨幣格式化
{{ 250 | currency }} // 結果:$250.00
{{ 250 | currency:"RMB ¥ " }} // 結果:RMB ¥ 250.00
5、filter查詢
// 查詢name為iphone的行
{{ [{"age": 20,"id": 10,"name": "iphone"},
{"age": 12,"id": 11,"name": "sunm xing"},
{"age": 44,"id": 12,"name": "test abc"}
] | filter:{'name':'iphone'} }}
6、limitTo 擷取
{{"1234567890" | limitTo :6}} // 從前面開始擷取6位
{{"1234567890" | limitTo:-4}} // 從後面開始擷取4位
7、orderBy排序
// 根id降序排
{{ [{"age": 20,"id": 10,"name": "iphone"},
{"age": 12,"id": 11,"name": "sunm xing"},
{"age": 44,"id": 12,"name": "test abc"}
] | orderBy:'id':true }} 或者 |orderBy:'-id'
// 根據id升序排
{{ [{"age": 20,"id": 10,"name": "iphone"},
{"age": 12,"id": 11,"name": "sunm xing"},
{"age": 44,"id": 12,"name": "test abc"}
] | orderBy:'id' }}
- 自定義過濾器–多引數
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("");
}
});
全域性API
- angular.lowercase();字串轉小寫
- angular.uppercase();字串轉大寫
- angular.isString();判斷給定的物件是否為字串,是(true),否(false)
- angular.isNumber();判斷給定的物件是否數字,是(true),否(false)
動畫
AngularJS 使用動畫需要引入 angular-animate.min.js 庫
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular-animate.min.js"></script>
還需在應用中使用模型 ngAnimate
<body ng-app="ngAnimate">
依賴注入
有以下五個方法:value,factory,service,provider,constant。
示例:
// 定義一個模組
var mainApp = angular.module("mainApp", []);
// 建立 factory "MathService" 用於兩數的乘積 provides a method multiply to return multiplication of two numbers
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
// 在 service 中注入 factory "MathService"
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
...
路由器:
通常我們的URL形式為 http://runoob.com/first/page,但在單頁Web應用中 AngularJS 通過 # + 標記 實現,例如:http://runoob.com/#/first
,AngularJS 路由 就通過 # + 標記 幫助我們區分不同的邏輯頁面並將不同的頁面繫結到對應的控制器上。
示例:
<html>
<head>
<meta charset="utf-8">
<title>AngularJS 路由例項 - 菜鳥教程</title>
</head>
<body ng-app='routingDemoApp'>
<h2>AngularJS 路由應用</h2>
<ul>
<li><a href="#/">首頁</a></li>
<li><a href="#/computers">電腦</a></li>
<li><a href="#/printers">印表機</a></li>
<li><a href="#/blabla">其他</a></li>
</ul>
<div ng-view></div>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
<script>
angular.module('routingDemoApp',['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/',{template:'這是首頁頁面'})
.when('/computers',{template:'這是電腦分類頁面'})
.when('/printers',{template:'這是印表機頁面'})
.otherwise({redirectTo:'/'});
}]);
</script>
</body>
</html>