標籤:style blog io color ar 使用 java sp 資料
指令
1、restrict:指令聲明四種表現形式:A(屬性)、C(類)、E(元素)、M(注釋),使用“restrict”來進行配置。
2、template:指令中產生的字串html模版
3、templateUrl:模版的地址
4、replace:將原指令所在標籤替換為模版內容時,是否儲存原指令html,為false時則將模版中內容插入原指令標籤中。
5、transclude:將原指令中間的內容移動到template中有“ng-transclude”指令所屬標籤位置,為true時,覆蓋模版中標籤,為false時,不覆蓋並且原指令中間內容丟棄。
6、scope:指令的範圍,有三種範圍表示方式:
① scope : { innerArgs : "args" } 獨立的指令範圍,不能擷取到父範圍。
② scope : false 繼承自父範圍。
③ scope : {
"argument1" : "@attribute", //將指令內部屬性與範圍變數進行單向綁定
"argument2" : "=attribute", //將指令內部屬性與範圍變數進行雙向繫結
"argument3" : "&func" //將運算式與範圍變數進行綁定
}
7、compile:進行dom操作與處理。
8、link:在指令內部進行元素的事件綁定與資料繫結。
9、controller:將指令中方法暴露給外部其他指令使用。
10、require:依賴於其他的指令名稱,用法: require : "^otherDirective"
應用:
<div ng-app="app"> <div ng-controller="demoCtrl"> <hello toname="elic" hi>這是指令中原來的內容</hello> <div hello toname="elic">這是指令中原來的內容</div> <div class="hello" toname="elic">這是指令中原來的內容</div> </div></div>
<script src="~/Scripts/angular.js"></script><script type="text/javascript"> var app = angular.module("app", []); app.directive("hello", function () { return { restrict: "ACE", template: ‘<div>Hello,How are you? <span ng-transclude>此內容被原指令中內容覆蓋</span></div>‘, transclude: false, //將原指令中間的內容嵌入到template中有“ng-transclude”指令的html中 //為false時,丟失原指令中內容,模版中內容正常顯示 controller: function ($scope) { $scope.userName = ""; this.say = function () { alert("hello指令調用:" + $scope.userName); } this.setName = function (name) { $scope.userName = name; } }, link: function (scope, element, attrs) { //參數順序不可亂,但名稱可自訂 var userName = attrs.toname; //標籤中定義的屬性為“toName”,但此處取屬性也要全部使用小寫 //scope.sayHello(userName); //調用範圍中的方法 scope.$apply(); //第一次調用會報“$apply already in progress”錯誤,不知道原因…… scope.$apply("sayHello(‘" + userName + "‘)"); //第二次調用成功 //element為angular封裝集 element.bind("click", function () { alert(userName); }); } }; }); app.directive("hi", function () { return { require: "^hello", //依賴於“hello”指令 //通過第四個參數,自動注入“hello”指令中的controller,名字可自訂 link: function (scope, element, attrs, helloCtrl) { helloCtrl.setName("demo"); helloCtrl.say(); } }; }); app.controller("demoCtrl", function ($scope) { $scope.sayHello = function (userName) { alert("Hello," + userName); } });</script>
AngularJS學習筆記二