標籤:
指令
1.指令本質上就是AngularJS拓展具有自訂功能的HTML元素的途徑。
通過自訂元素來建立指令,如:<my-directive></my-directive>
.directive(‘myDirective‘,function(){
return{
restrict:‘E‘,
replace:true, //此句可不加
template:‘<a href="http://baidu.com">clickMe</a>‘
};
});
結果:clickMe點擊後跳轉到百度頁面
其中,restrict告訴AngularJS在編譯HTML時用哪種聲明格式來匹配指令定義,可以同時指定一個或多個格式,主要有元素(E)、屬性(A)、類(C)和注釋(M),絕大部分情況下使用A,因為有較好的跨瀏覽器安全色性
replace方法會用自訂元素取代指令聲明,而不是嵌套在其內部。
2.內建指令
(1)布爾屬性
當這個屬性出現時,屬性值就為true,不出現就為false。在AngularJS中使用動態資料綁定時,不能簡單的將屬性值設定為true或false,通過運算運算式的值來決定在目標元素上是插入還是移除對應的屬性
a.ng-disabled
使用ng-disabled可以把disabled屬性綁定到以下表單輸入欄位上:
<input>(text,checkbox,radio,number,url,email,submit) <textarea> <select> <button>
如:<input type="text" ng-model="property" >
<button ng-disabled="!property">aButton</button>
按鈕一直會禁用,直到使用者在文字欄位中輸入內容。
b.ng-readonly
<input type="text" ng-model="myproperty" >
<input type="text" ng-readonly="myproperty" value="some text here" />
$scope.myproperty="";
當input中輸入值後,第二個Input值為唯讀
c.ng-checked
<label>someproperty={{someProperty}}</label>
<input type="checkbox" ng-checked="someProperty" ng-init="someProperty=true" ng-model="someProperty" />
ng-init將someProperty初始化為true,即ng-checked為true,someproperty=true,即checkbox已經選中
d.ng-selected
對是否出現option標籤的selected屬性進行綁定
<label>Select two Fish:</label>
<input type="checkbox" ng-model="isTwoFish"><br />
<select>
<option>one Fish</option>
<option ng-selected="isTwoFish">Two Fish</option>
</select>
將checkbox點擊後會自動選上Two Fish
(2)類布爾屬性
a.ng-href
當使用當前範圍中的屬性動態建立URL時,應用ng-href代替href
有個潛在問題是當使用者點擊一個由插值動態產生的連結時,如果插值未生效,就會跳轉到錯誤的頁面
b.ng-src
瀏覽器在ng-src對應的運算式生效之前不會載入映像
<body ng-app="myapp">
<h1>Rightway</h1>
<img ng-src="{{imgSrc}}" />
</body>
angular.module("myapp",[])
.run(function($rootScope,$timeout){
$timeout(function(){
$rootScope.imgSrc=‘360反饋意見17060225202456.png‘;
},2000);
});
3.在指令中使用子範圍
ng-app和ng-controller是特殊的指令,因為它們會修改嵌套在它們內部的指令的範圍
(1)ng-app
任何具有ng-app屬性的DOM元素將被標記為$rootscope的起始點
$rootscope是範圍鏈的起始點,任何嵌套在ng-app內的指令都要繼承它,可以通過run方法來訪問$rootscope
(2)ng-controller
為嵌套在其中的指令建立一個子範圍,避免將所有操作和模型都定義在$rootScope上
$scope對象的職責是承載DOM中指令所共用的操作和模型,模型指的是$scope上儲存的包含瞬時狀態資料的javascript對象,持久化狀態的資料應該儲存到服務中。
<body ng-app="myapp">
<div ng-controller="SomeController">
{{someBareValue}}
<button ng-click="someAction()">
Communicate to child
</button>
<div ng-controller="ChildController">
{{someBareValue}}
<button ng-click="childAction()">
Communicate to parent
</button>
</div>
</div>
</body>
angular.module("myapp",[])
.controller("SomeController",function($scope){
$scope.someBareValue="hello computer";
$scope.someAction=function(){
$scope.someBareValue="hello human,from parent";
};
})
.controller("ChildController",function($scope){
$scope.childAction=function(){
$scope.someBareValue="hello human,form child";
};
});
hello computer
Communicate to child //實際效果為button
hello computer
Communicate to parent //實際效果為button
點擊父button,兩個值都為hello human,from parent,再點擊子button,子button的那塊顯示hello human,form child,導致兩次值不一樣。
實際開發中採用以下方法保持資料的一致性:
<body ng-app="myapp">
<div ng-controller="SomeController">
{{someModel.someValue}}
<button ng-click="someAction()">
Communicate to child
</button>
<div ng-controller="ChildController">
{{someModel.someValue}}
<button ng-click="childAction()">
Communicate to parent
</button>
</div>
</div>
</body>
angular.module("myapp",[])
.controller("SomeController",function($scope){
$scope.someModel={
someValue:‘hello computer‘
}
$scope.someAction=function(){
$scope.someModel.someValue="hello human,from parent";
};
})
.controller("ChildController",function($scope){
$scope.childAction=function(){
$scope.someModel.someValue="hello human,form child";
};
});
點擊Communicate to child,結果都為hello human,from parent,點擊Communicate to parent ,結果都為hello human,from parent
原因:JS對象中,字串、數字和布爾型變數是值複製,而數組、對象和函數使引用複製。由於原型繼承的關係,修改父級對象中的someBareValue會同時修改子物件中的值,但是反之就不行。而如果將模型對象的某個屬性設定為字串,就可以通過引用進行共用,在子$scope中修改屬性也會修改父$scope中的屬性。
(3)ng-include
可以載入、編譯並包含外部HTML片段到當前的應用中,此時會自動建立一個子範圍,可以在同一個DOM元素上添加一個ng-controller指令。
<div ng-include="/myTemp.html" ng-controller="myCtrl" ng-init="name=‘world‘">
Hello {{name}}
</div>
(4)ng-switch
這個指令要與ng-switch-when及on="propertyName"一起使用
<div ng-controller="myCtrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<div ng-switch on="selection">
<div ng-switch-when="settings">Settings div</div>
<div ng-switch-when="home">home div</div>
<div ng-switch-default="other">default</div>
</div>
</div>
angular.module(‘myapp‘,[])
.controller(‘myCtrl‘, function($scope) {
$scope.items=[‘settings‘,‘home‘,‘other‘];
$scope.selection=$scope.items[0];
});
(5)ng-view
用來設定將被路由管理和放置在HTML中的視圖的位置
(6)ng-if
可以根據運算式的值在DOM中產生或移除一個元素。當ng-if的運算式為false時,這個DOM元素會被移除,運算式再次為true時這個元素及其內部的子項目會被重新載入DOM,此時的狀態會是它們的原始狀態,而不是上次被移除時的狀態。
(7)ng-repeat
用來遍曆一個集合或為集合中的每個元素產生一個模板執行個體,主要有以下用法:
$index 遍曆的進度 $first 當元素是遍曆的第一個值時為true
$last $middle $even(index為偶數) $odd(index為奇數)
<body ng-app="myapp" ng-controller="ctrl01">
<div style="padding: 10px;font-weight: bold;">地址管理</div>
<ul>
<li ng-repeat="a in list">
<h4>{{$index+1+"."+a.address+$first}}</h4>
</li>
</ul>
</body>
angular.module("myapp",[])
.controller(‘ctrl01‘,function($scope){
$scope.list=[
{id:1,address:‘蓮花路1號‘},
{id:2,address:‘建設路3號‘},
{id:3,address:‘興化路7號‘},
{id:4,address:‘北京鳥巢‘}
];
})
(8){{}}
是AngularJS內建的模板文法,實際上也是指令,是ng-bind的簡略形式。在螢幕可視的地區使用{{}}會導致頁面載入時未渲染的元素髮生閃爍,使用ng-bind可以避免這個問題
(9)ng-bind
<body ng-init="greeting=‘helloWorld‘">
<p ng-bind="greeting"></p>
</body>
(10)ng-cloak
也可以避免未渲染元素閃爍,會將內部元素隱藏,直到路由調用對應的頁面時才顯示出來
<body ng-init="greeting=‘helloWorld‘">
<p ng-cloak>{{greeting}}</p>
</body>
(11)ng-bind-template
可以在視圖中綁定多個運算式
<div ng-bind-template="{{message}}{{name}}"></div>
(12)ng-model
(13)ng-show/ng-hide
(14)ng-change
<body ng-app="myapp">
<div ng-controller="EquationController">
<input type="text" ng-model="equation.x" ng-change="change()" />
<code>{{equation.output}}</code>
</div>
</body>
angular.module("myapp",[])
.controller("EquationController",function($scope){
$scope.equation={};
$scope.change=function(){
$scope.equation.output=parseInt($scope.equation.x)+2;
};
})
(15)ng-form
用來在一個表單內部嵌套另一個表單,這就意味著內部所有的子表單都合法時,外部的表單才會合法。
不能通過字元插值來輸入元素動態產生name屬性,所有需要將ng-form指令內每組重複的輸入欄位都包含在一個外部表格單元素內。可以使用ng-repeat動態建立表單
CSS類會根據表單的驗證狀態自動化佈建:
合法時設定:ng-valid 不合法時設定:ng-invalid
未修改時設定:ng-prition 修改時設定:ng-dirty
指定表單提交時使用下面兩個指令中的一個:
ng-submit ng-click
使用ng-loop來遍曆從伺服器取回的所有資料,由於不能動態產生name屬性,又需要這個屬性做驗證,所以在迴圈的過程中會為每一個欄位都產生一個新表單。
例:
<html ng-app="myapp">
<head>
<meta charset="utf-8" />
<title></title>
<style>
input.ng-invalid{
border: 1px solid red;
}
input.ng-valid{
border: 1px solid green;
}
</style>
</head>
<body>
<form name="form" ng-controller="FormController" ng-submit="submitForm()" novalidate>
<div ng-repeat="field in fields" ng-form="form_input">
<input type="text" name="dynamic_input" ng-required="field.isRequired" ng-model="field.name"
placeholder="{{field.placeholder}}" />
<div ng-show="form_input.dynamic_input.$dirty && form_input.dynamic_input.$invalid">
<span class="error" ng-show="form_input.dynamic_input.$error.required">The field is required.</span>
</div>
</div>
<button type="submit" ng-disabled="form.$invalid">Submit All</button>
</form>
</body>
angular.module("myapp",[])
.controller("FormController",function($scope){
$scope.fields=[
{placeholder:‘Username‘,isRequired:true},
{placeholder:‘Password‘,isRequired:true},
{placeholder:‘Email(optional)‘,isRequired:false},
];
$scope.submitForm=function(){
alert("it works!");
};
});
(16)ng-click
<body>
<div ng-controller="CounterCtrl">
<button ng-click="count=count+1" ng-init="count=0">
Increment
</button>
count:{{count}}
<button ng-click="decrement()">Decrement</button>
</div>
</body>
angular.module(‘myapp‘,[])
.controller("CounterCtrl",function($scope){
$scope.decrement=function(){
$scope.count=$scope.count-1;
};
})
兩個button,點擊Increment加1,點擊Decrement減1
(17)ng-select
將資料同HTML的<select>元素進行綁定,可以和ng-model以及ng-options指令一同使用。
ng-options的值可以是一個內涵運算式,也就是說可以接受一個數組或對象,並對它們進行迴圈,將內部的內容提供給select標籤內部的選項
<body>
<div ng-controller="CityController">
<select ng-model="city" ng-options="city.name for city in cities">
</select>
Best City: {{ city.name }}
</div>
</body>
angular.module(‘myapp‘,[])
.controller(‘CityController‘, function($scope) {
$scope.cities = [
{name: ‘Seattle‘},
{name: ‘San Francisco‘},
{name: ‘Chicago‘},
{name: ‘New York‘},
{name: ‘Boston‘}
];
});
(18)ng-submit
(19)ng-class
動態設定元素的類,方法是綁定一個代表所有需要添加的類的運算式,重複的類不會添加。當運算式發生變化,先前添加的類會被移除,新類會被添加
<style>
.red{
background-color: red;
}
</style>
<body>
<div ng-controller="LotteryController">
<div ng-class="{red:x>5}" ng-if="x>5">You won!</div>
<button ng-click="x=generateNumber()" ng-init="x=0">
Drew Number!
</button>
<p>Number is:{{x}}</p>
</div>
</body>
angular.module(‘myapp‘,[])
.controller(‘LotteryController‘, function($scope) {
$scope.generateNumber=function(){
return Math.floor((Math.random()*10)+1);
};
});
angularJS 指令一