Angular 1.x 精華一頁紙

AngularJS/Vue/React 都是通過JS利用H5自定義標籤和屬性的能力,提供一些指令和邏輯控制,實現界面邏輯。所以他們在很多設計方面都有相似點。

1、典型用法


I、基本架構
HTML5 部分 -- 引入應用和控制器,並指定其作用域
<script src="angular.js"/>
<script src="my.js"/>
<div ng-app="myApp" ng-controller="myCtrl">

</div>

JS部分
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});

使用模塊定義應用app,並創建controller控制器
如果有依賴模塊,angular.moduel('myApp',['依賴的模塊']);

II、作用域 $scope 控制器controller和 HTML5元素 交互的中介
可以在 $scope 中定義數據/函數,然後在 HTML5 元素中使用;反過來,也可以通過 $scope 引用HTML5 中的因素
a、每個controller 都有一個 $scope
b、全局有一個 $rootScope,各個控制器直接如果想共享數據則通過 $rootScope

app.controller('myCtrl', ['$scope','$rootScope',function($scope,$rootScope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
$scope.inc = function(){
}
}]);

2、概念


I、參數 - 數據存取
{{ 變量名 }}
支持表達式操作

{{ Number + 1}}
{{ firstName + '-' + lastName }}
{{ i > 0 ? 1 : 0}}

II、邏輯控制
a、迭代
<ng-repeat>
<ul>
<li ng-repeat="x in names">
<p id="x{{$index}}" class="x.name">
{{ x.name + ', ' + x.country }}</p></li>
</ul>

b、條件判斷
<ng-if> 可以控制當前的元素是否出現

經典的表格處理
<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>

從基本頁面邏輯處理看,angularJS和Vue的用法是一致的。

3、綁定


I、模型ng-model - 表單數據綁定 (雙向綁定)
其實,雙向綁定非常類似 Java中的 JavaBean ,JavaBean的變化影響到具體的展示,同樣具體的展示也會影響JavaBean的值,典型的應用比如在ORM中,或者JSP中

<form ng-app="" name="myForm">
輸入你的名字:
<input name="myAddress" ng-model="text" required>
</form>

$scope.text = [];

II、數據綁定/元素綁定 ng-bind
<p>剩餘字數: <span ng-bind="left()"></span></p>
-- 這個例子是兩者使用區別最直觀的,ng-model 綁定一個參數,然後在js中使用(也可以反向影響),這裏的HTML的value是 主動觸發的,ng-bind 從 js提供一個方法/值, HTML 的值是被動使用的

ng-bind是從$scope -> view的單向綁定
ng-modle是$scope <-> view的雙向綁定

從綁定數據來看,angularJS和Vue也是一致的。

4、邏輯-事件-控制


前面沒有展開來說,從這裏詳細描述一下
a、從作用域來說,Vue並沒有做明確說明,可以認爲是一個Vue對象就是一個作用域;而angularJS 則定義了scope作用域和普通js數據區分開來
b、顯式的在 模塊基礎上 定義了 控制器,這是Vue沒有的
c、把 方法 分爲 控制器和服務,做了區分, 控制器需要 DI 依賴注入(這是Spring的設計理念也用在這裏)服務才能使用,這點 Vue 也沒有做特殊處理
從這些來看,angularJS 要比 Vue 複雜的多

更多依賴注入的問題,後面再詳細描述

I、ng-xxx指令+ 控制器方法

<div ng-app="myApp" ng-controller="personCtrl">
<button ng-click="toggle()">隱藏/顯示</button>
<p ng-hide="myVar">
名: <input type=text ng-model="firstName"><br>
姓: <input type=text ng-model="lastName"><br><br>
姓名: {{firstName + " " + lastName}}
</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
}
});
</script>

II、其他方法

過濾器
AngularJS 使用了 管道符 | 用來過濾數據 -- 和Linux類似,Vue也類似

filter -- 選擇子集
lowerCase/uppercase -- 大小寫轉換
orderBy -- 排序
currency -- 轉換爲貨幣形式

<li ng-repeat="x in names | filter:test | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>


5、表單元素



同Vue一樣,通過 ng-model 綁定數據

比如文本輸入框:<input type="text" ng-model="user.firstName"><br>
Last Name:<br>

6、組件化


angularJS通過自定義指令來實現組件化的功能,和Vue的自定義指令不是一個概念。

I、典型例子

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
var app = angular.module("myApp", []);
app.directive("caption", function() {
return {
template : '<span>{{x.name}}</span>'
};
});
</script>
</head>
<body>

<div ng-app="myApp" ng-init="names=[{name:'Jani',country:'Norway'}]">

<p>循環對象:</p>
<ul>
<li ng-repeat="x in names">
<p caption></p>
{{ x.name + ', ' + x.country }}
</li>
</ul>

II、組件化的步驟

一、註冊一個組件
a、定義組件 通過模塊的指令 app.directive("caption", function(){});
b、定義組件類型 restrict: 'E', 指定是 屬性還是標籤
c、定義控制器,裏面定義一些邏輯
d、編譯 complie 方法,在模版替換的各個生命週期階段,可以有回調函數

二、使用 template 進行替換 標籤元素
三、父控件(外層) 傳遞數據給 子控件(內層),通過 在 scope中定義的 屬性,可以直接把數據傳給內層
四、子控件(內層) 傳遞數據給父控件(外層),通過事件來傳遞
使用 scope.$broadcast 把事件廣播出去, scope.$on 監聽事件
使用 scope.$watch 觸發事件

其中,二、三、四步,angularJS和Vue極其相似,只是在第一步,angularJS 明顯複雜很多

define(['angular','bootstrap','css!test.style.control'], function() {

var showpane = angular.module('test.app.control',[])
showpane.directive('testShowpane', function() {
return {
restrict: 'E',
transclude: true,
scope: {
data : '=',
},
controller: [ "$scope", function(scope) {
var scrolls = scope.scrolls = scope.data;
console.log(scrolls);
}],
compile: function(tEle, tAttrs) {
console.log(tEle.html());
return {
pre: function(scope, iElem, iAttrs){
console.log('pre link => ' + iElem.html());
},
post: function(scope, iElem, iAttrs){
console.log('post link => ' + iElem.html());
_link(scope, iElem, iAttrs);
}
}
},

template:
'<div class="showpane container">\
<div ng-repeat="scroll in data" class="pane " style="{{heightStyle}}">\
<div class="row"><div class="kpititle col-xs-12 col-sm-12 col-md-12 col-lg-12">{{scroll.title}}</div></div>\
<div class="row">\
<div class="progress col-xs-8 col-sm-8 col-md-8 col-lg-8 ">\
<div class="progress-bar" ng-class="{\'progress-bar-success\':{{scroll.type == 0}},\'progress-bar-warning\':{{scroll.type == 1}},\'progress-bar-danger\':{{scroll.type == 2}}}" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: {{scroll.percent}}%;">\
</div>\
</div>\
<div><div class="kpivalue col-xs-4 col-sm-4 col-md-4 col-lg-4">{{scroll.valuedisp}}</div></div>\
</div>\
</div>\
</div>',
replace: true
};

function _link(scope, iElem, iAttrs){

function percentHeight(num){
return (Math.round(1 / num * 10000) / 100.00 + "%");
}

scope.$watch('data', function(newValue,oldValue) {
if (scope.data) {
scope.heightStyle = "height:" + percentHeight(newValue.length) +";";
scope.$broadcast("datachange", newValue);
}
}, true);

scope.$on('datachange',function (event, msg) {
console.log(msg);
});

}
});

return showpane;
});

7、其他


I、ng-option 下拉框

II、表單驗證
所有表單都有 這幾個屬性,以及對應的方法驗證 $dirty/$invalid/$error

III、全局API
比較 isArray/ isDate/ isNumber ...
轉換 formJSON /toJSON 可以把Json序列化成字符串,也可以把字符串反序列化成 Json
迭代 foreach
系統 bootstrap 啓動/ element 獲取 HTML DOM

其他常見指令

IV、控制元素可視化 ng-disabled/ng-show/ng-hidd

V、包含文件
<div ng-include="'myUsers_List.htm'"></div>
--模塊話的一種方式,把重複的代碼在這裏模塊化

完整的angular 組件化 例子可以見參見《完整的客戶端組件化案例 angularJS + requireJS

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章