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

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

使用angular指令能夠本身擴展html語法,還能夠作不少自定義的事情.在後面會專門講解這一塊的知識,這一篇只是起到了解入門的做用.html

與控制器,過濾器,服務,同樣,能夠經過模塊實例的directive的方法來建立指令:html5

var someModule = angular.module('SomeModule',[]);數組

someModule.directive('directiveName',function(){app

     return {函數

         link: function(scope,elements,attrs,controller){spa

         }3d

     }code

});htm

directive傳入兩個參數:

第一個參數是指令的名字;

第二個參數是一個工廠函數:

函數返回一個對象,對象的link方法的函數有四個參數:

scope:獲取外層scope的引用

elements:它所存在的DOM元素

attrs:傳遞給指令的一個屬性數組

controller:DOM元素上的控制器

 

下面來看個簡單的小例子,在html5中,元素有autofocus屬性,添加了這個屬性的元素,會自動獲取焦點.咱們能夠使用angular來寫一個這樣的指令:

咱們讓第二個button在打開的時候就獲取焦點,因此按回車就至關於點擊了這個按鈕:

<!DOCTYPE html>
<html ng-app="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">
    *{
      font-family:'MICROSOFT YAHEI';
      font-size:12px
    }
  </style>
</head>
<body>
<div ng-controller="focus">
  <button ng-click="nofocus()">沒有焦點</button>
  <br/>
  <button myautofocus ng-click="hasfocus()">有焦點</button>
  <br/>
  <br/>
  <span>{{text}}</span>
</div>
</body>
</html>
var autoFocus = angular.module('AutoFocus',[]);
autoFocus.controller('focus',function($scope){
    $scope.text="沒有點擊任何按鈕";
    $scope.nofocus = function(){
        $scope.text="沒有點擊任何按鈕";
    };
    $scope.hasfocus = function(){
        $scope.text="點擊了有焦點按鈕";
    };
});
autoFocus.directive('myautofocus',function(){
    return {
        link: function(scope,elements,attrs,controller){
            elements[0].focus();
        }
    }
});

一.建立模塊AutoFocus

二.經過模塊的controller方法建立控制器focus

三.經過模塊的directive方法建立指令myautofocus

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

 

效果截圖:

打開頁面時:

 

按下回車後:

相關文章
相關標籤/搜索