// Create an application module for our demo.
var app = angular.module( "Demo", [] );
// I add an element to the point of a click and then randomly select one of the
// existing elements in the lsit.
app.directive("bnDemo",function() {
// Create a jQuery plugin to help with the demo. Since we are including
// jQuery in our application, "angular.element" is a reference to the
// jQuery object, which means we can define plugins off the "element".
angular.element.fn.random = function() {
return( this.eq( Math.floor( this.length * Math.random() ) ) );
};
// Create a jQuery plugin to help set the position of the elements in
// the collection based on a pixel-based X/Y coordinates and an optional
// offset that is added to both the coordinate values.
angular.element.fn.xyo = function( x, y, offset ) {
this.css({
left: ( ( x + ( offset || 0 ) ) + "px" ),
top: ( ( y + ( offset || 0 ) ) + "px" )
});
return( this );
};
// Return the directive configuration.
return({
link: link,
restrict: "A"
});
// ---
// PUBLIC METHODS.
// ---
// I bind the JavaScript events to the local scope.
function link( scope, element, attributes ) {
element.on("click",function handleClickEvent(event){
// If the user clicked on an existing LI, then don't change
// the contents of the container, just select the target.
if (angular.element( event.target ).is( "li" )){
// Select the target element.
element.children()
.removeClass( "selected" )
.filter( event.target )
.addClass( "selected" )
;
return;
}
// Create a new element at the click position.
angular.element( "<li></li>" )
.xyo( event.pageX, event.pageY, -25 )
.appendTo( element )
;
// Select a random element in the...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.