angular學習筆記 十九 指令修改dom

2022-03-17 22:02:47 字數 2173 閱讀 6551

本篇主要介紹angular使用指令修改dom:

使用angular指令可以自己擴充套件html語法,還可以做很多自定義的事情.在後面會專門講解這一塊的知識,這一篇只是起到了解入門的作用.

與控制器,過濾器,服務,一樣,可以通過模組例項的directive的方法來建立指令:

var somemodule = angular.module('somemodule',);

somemodule.directive('directivename',function());

directive傳入兩個引數:

第乙個引數是指令的名字;

第二個引數是乙個工廠函式:

函式返回乙個物件,物件的link方法的函式有四個引數:

scope:獲取外層scope的引用

elements:它所存在的dom元素

attrs:傳遞給指令的乙個屬性陣列

controller:dom元素上的控制器

下面來看個簡單的小例子,在html5中,元素有autofocus屬性,新增了這個屬性的元素,會自動獲取焦點.我們可以使用angular來寫乙個這樣的指令:

我們讓第二個button在開啟的時候就獲取焦點,所以按回車就相當於點選了這個按鈕:

doctype html

>

<

html

="autofocus"

>

<

head

>

<

title

>16.1使用指令修改dom

title

>

<

meta

charset

="utf-8"

>

<

script

src="../angular.js"

>

script

>

<

script

src="script.js"

>

script

>

<

style

type

="text/css"

>

*style

>

head

>

<

body

>

<

div

ng-controller

="focus"

>

<

button

ng-click

="nofocus()"

>沒有焦點

button

>

<

br/>

<

button

myautofocus ng-click

="hasfocus()"

>有焦點

button

>

<

br/>

<

br/>

<

span

>}

span

>

div>

body

>

html

>

var autofocus = angular.module('autofocus',);

autofocus.controller('focus',function

($scope);

$scope.hasfocus = function

();});

autofocus.directive('myautofocus',function

() }

});

一.建立模組autofocus

二.通過模組的controller方法建立控制器focus

三.通過模組的directive方法建立指令myautofocus

myautofocus的工廠函式就是實現元素自動獲取焦點這一功能

效果截圖:

開啟頁面時:

按下回車後:

angular指令筆記 ng options

1 ng options指令用途 在表示式中使用陣列或物件來自動生成乙個select中的option列表。ng options與ng repeat很相似,很多時候可以用ng repeat來代替ng options。但是ng options提供了一些好處,例如減少記憶體提高速度,以及提供選擇框的選項來...

angular 學習筆記 2 ng指令

今天介紹一些常用的ng指令吧。一 ng bind和ng clock。ng bind 將data資料繫結到當前元素的 innerhtml,相當於初始化吧。ng clock 主要用來避免html模板顯示引起的不希望的閃爍效應,其實ng bind也有同樣的效果。解決閃爍問題還可以把引包放在head裡面,先...

angular學習筆記(6) 指令

angular1學習筆記 6 指令 restrict 匹配模式 1.a 屬性 2.m 注釋 3.e 元素 4.c 樣式類 注釋留空兩邊 推薦使用元素和屬性的方式使用指令 當需要建立帶有自己的模板的指令時,使用元素名稱的方式建立指令 當需要為已有的html標籤增加功能時,使用屬性的方式建立指令 sco...