#HannoverJS 28th Mar '13
And I like that!
Directives are a way to teach HTML new tricks!
// The code you actually use
<h2>Drag the heart!</h2>
<div draggable></div>
app.directive('draggable', function($document) {
var startX=0, startY=0, x = 0, y = 0;
return function(scope, element, attr) {
element.css({
position: 'relative',
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);
}
}
});
<tabs>
<tab title="Tab 1">
Angular is what?!
</tab>
<tab title="Tab 2">
Awesome.
</tab>
</tabs>
Click around and have some fun with it...
<zippy title="Click to toggle">
Zippy's content
</zippy>
<zippy title="Let's kick some asses!">
<zippy title="WTF...?!">
<zippy title="Nesting?">
.... and so on
</zippy>
</zippy>
</zippy>
Yeap.
Think of angular as a better browser rather then a framework.
- Miško Hevery
To see a list of built-in directives click the link below, check out the 'directive' section on the left and try out the examples.
window.onload = function() {
var $rootElement = angular.element(window.document);
var modules = [
'ng',
'myApp',
function($provide) {
$provide.value('$rootElement', $rootElement)
}
];
var $injector = angular.injector(modules);
var $compile = $injector.get('$compile');
var compositeLinkFn = $compile($rootElement);
var $rootScope = $injector.get('$rootScope');
compositeLinkFn($rootScope);
$rootScope.$apply();
}
var app = angular.module('myApp', []);
app.directive('directiveName', function factory(injectables) {
return function linkFn(scope, iElement, iAttrs) {
// Logic which has access to instance element,
// scope and instance attributes
};
});
var app = angular.module('myApp', []);
app.directive('alertFoo', function () {
return function (scope, element, attrs) {
element.bind('hover', function () {
alert('foo');
});
);
});
<ANY foo></ANY>
<ANY foo class="foo"></ANY>
Working sample? Click here!
var app = angular.module('myApp', []);
app.directive('foo', function () {
return {
priority: 0,
template: '<div></div>',
templateUrl: 'template.html',
replace: false,
transclude: false,
restrict: 'A',
scope: false,
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function (scope, iElement, iAttrs, controller) {}
post: function (scope, iElement, iAttrs, controller) {}
}
},
link: function postLink(scope, iElement, iAttrs) {}
};
});
...define directives as attribute
...define directives as class
...define directives as element
...define directives as comment
...and there's more
<zippy title="Click to toggle">
Zippy's content
</zippy>