现在的位置: 首页 > 综合 > 正文

angularJS开发指南(angularJS developer guide) 之二

2014年08月16日 ⁄ 综合 ⁄ 共 2341字 ⁄ 字号 评论关闭

Directive 指令

A directive is a behavior which should be triggered when specific HTML constructs are encountered in the compilation process. The directives can be placed in element names, attributes, class names, as well as comments. Here are some equivalent examples of invoking the ng-bind directive.

大致意思::指令是当关联的HTML结构进入编译阶段时应该执行的操作。指令可以写在很多地方<span ng-bind="exp"></span>

<span class="ng-bind: exp;"></span>
<ng-bind></ng-bind>
<!-- directive: ng-bind exp -->
<!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>
</body>
</html>
scirpt.js
angular.module('drag', []).
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);
}

Understanding View 理解视图
There are many templating systems out there. Most of them consume a static string template and combine it with data, resulting in a new string. The resulting text is then innerHTMLed into an element.
网上有很多模板系统,很多就是将静态的字符模板和数据绑定,生成新字符,然后通 过innerHTML插入到页面元素中”

如下图所示:

这样有很多不同的地方,比如,任何数据的改变,都要重新组装新字符,然后写入到页面元素中
Angular is different. The Angular compiler consumes the DOM with directives, not string templates. The result is a linking function, which when combined with a scope model results in a live view. The view and scope model bindings are transparent. No action
from the developer is needed to update the view. And because no innerHTML is used there are no issues of clobbering user input. Furthermore, Angular directives can contain not just text bindings, but behavioral constructs as well.
angular 不是这样的,AngularJS编译器使用的是带指令的DOM。
如下图所示:

The Angular approach produces a stable DOM. This means that the DOM element instance bound to a model item instance does not change for the lifetime of the binding. This means that
the code can get hold of the elements and register event handlers and know that the reference will not be destroyed by template data merge.
AngularJS会生成一个“稳定的DOM”。也就是说DOM元素的实例不会在生命周期中改变。也就是说代码中可以获取到DOM元素并注册事件,不用担心模板和数据丢失。

抱歉!评论已关闭.