angularJS Directive学习

Directive 指令

直接上实例

index.html

<!doctype html>
<html ng-app="drag">
  <head>
    <script src="http://code.angularjs.org/angular-1.1.0.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <span draggable>Drag ME</span>

<div enter>I am Directive</div>
</body> </html>

script.js:

var dragDir=angular.module('drag', []);
dragDir.directive("enter", function () {
    return function (scope, element) {
        element.bind("mouseenter", function () {
            alert("enter");
        });
    };
}); dragDir.directive(
'draggable', function($document) { var startX=0, startY=0, x = 0, y = 0; return function(scope, element, attr) { element.css({ position: 'relative', border: '1px solid red', backgroundColor: 'lightgrey', cursor: 'pointer' }); element.bind('mousedown', function(event) { startX = event.screenX - x; startY = event.screenY - y; $document.bind('mousemove', mousemove); $document.bind('mouseup', mouseup); }); function mousemove(event) { y = event.screenY - startY; x = event.screenX - startX; element.css({ top: y + 'px', left: x + 'px' }); } function mouseup() { $document.unbind('mousemove', mousemove); $document.unbind('mouseup', mouseup); } } });

oK!然后来学习一些概念性的东西!

指令”:

AngularJS的HTML编译器能让浏览器识别新的HTML语法。它能让你将行为关联到HTML元素或者属性上,甚至能让你创造具有自定义行为的新元素。AngularJS称这种行为扩展为“指令

指令指示的是“当关联的HTML结构进入编译阶段时应该执行的操作”。本质上只是一个当编译器编译到相关DOM时需要执行的函数

编译器(complier):

编译器是AngularJS提供的一项服务,它通过遍历DOM来查找和它相关的属性。整个编译的过程分为两个阶段。

  • 编译: 遍历DOM并且收集所有的相关指令,生成一个链接函数。

  • 链接: 给指令绑定一个作用域,生成一个动态的视图。作用域模型的任何改变都会反映到视图上,并且视图上的任何用户操作也都会反映到作用域模型。这使得作用域模型成为你的业务逻辑里唯一要关心的东西。

原文地址:https://www.cnblogs.com/yujian-bcq/p/3840115.html