Drag and drop ordering with ng-repeat - angularjs

This is my html:
<div ng-repeat="activity in activities">
<button id="{{activity.id}}" activity=activity draggable>
{{activity.name}}
</button>
</div>
<div droppable handle="handleDrop(activity)">
<div ng-repeat="activity in getAll()">
<button>
{{activity.name}}
</button>
</div>
</div>
As you see I have two directives, draggable and droppable. The draggable directive sends the activity data to the droppable directive via dataTransfer. On the event 'drop', the data (the activity JSON) is added to a controller and getAll() returns all dropped activities. Now, this works. But I cannot change the order of these activities, since the drop only pushes the activity to a list. What should I do if I want to be able to put one activity in between two activities, or perhaps rearrange them?
EDIT:
app.directive('droppable', function () {
return {
scope: {
handle: '&'
},
link: function (scope, element) {
element.on('dragover', function (e) {
e.preventDefault();
});
element.on('drop', function (e) {
e.preventDefault();
var activity = JSON.parse(e.originalEvent.dataTransfer.getData("text"));
scope.handle({activity: activity});
scope.$apply();
});
}
};
});
app.directive('draggable', function () {
return {
scope: {
'activity' : '='
},
link: function (scope, element) {
var el = element[0];
el.draggable = true;
el.addEventListener('dragstart', function (e) {
e.dataTransfer.setData("text", JSON.stringify(scope.activity));
}, false);
}
}
});

I found a solution myself. What I did was to add this to the html draggable element:
data-index="{{$index}}"
Then, in the draggable directive in the dragenter event, I added:
if(e.target.hasAttribute('draggable')) {
e.target.classList.add('insert');
}
Where the insert class adds some styling to show that the user is about to drop between two elements. And in the drop event, I added:
var i = e.target.getAttribute('data-index');
if (i !== null) {
scope.handle({activity: activity, index: i});
} else {
scope.handle({activity: activity});
}
scope.$apply();
This solved it for me. Perhaps it could be useful to someone.

Related

ng-click does not work in directive of inline magnific popup

I have created magnific popup directive in angularjs. It works fine ng-click event on description link when first time loads but after close popup and again click on description link it does not work.
Please refer below code:
PhotoCtrl.js
(function () {
'use strict';
function PhotoCtrl($rootScope, $scope, $state, HzServices, HzPhotoService) {
$scope.doAlbumList = function () {
var data = {q: $state.params.pid};
$scope.albums = {};
$scope.albumsCount = 0;
$scope.photos = {};
$scope.photosCount = 0;
$rootScope.arrData = [];
var deferred = HzServices.deferred("/api/album/list", 'GET', data);
deferred.then(
function (res) {
/*
* success in repsonse
* Share common photo & album data across all controllers, directives by services.
*/
var data = {album: {count: res.data.count.album, data: res.data.album}, photo: {count: res.data.count.photo, data: res.data.photo}};
/*
* Create an array of magnific inline popup content
*/
angular.forEach(data.photo.data, function (value, key) {
if (value.data.length > 0) {
angular.forEach(value.data, function (value_, key_) {
$rootScope.arrData.push({
imageDescription: value_.photo_description,
imageScale_img: "/resize/" + value_.module + "/" + value_.photo_name,
imageOriginal_href: "/" + value_.module + "/" + value_.photo_name
});
});
}
});
HzPhotoService.setSharedData(data);
$scope.albums = $rootScope.sharedData.album.data;
$scope.albumsCount = $rootScope.sharedData.album.count;
$scope.photos = $rootScope.sharedData.photo.data;
$scope.photosCount = $rootScope.sharedData.photo.count;
},
function (res) {
/*
* Error hading in repsonse
*/
var data = {album: {count: $scope.albumsCount, data: $scope.albums}, photo: {count: $scope.photosCount, data: $scope.photos}};
HzPhotoService.setSharedData(data);
}
);
}
/**
* Get Photos data & count
* #returns {Array}
*/
$scope.doGetPhoto = function () {
return [{photos: $scope.photos, photoCount: $scope.photoCount}];
}
$scope.doEditDescription = function () {
console.log("description links from controller called");
}
angular
.module("AppWhizbite")
.controller('PhotoCtrl', ['$rootScope', '$scope', '$state', 'HzServices', 'HzPhotoService', PhotoCtrl]);
}());
photoList.html
<div>
<div class="total_album_photo gallery" ng-repeat-start="photo in photos track by $index">
<div class="no_of_photo imgWrapper">
<a href="javascript:void(0);" class="popup-link" data-index="{{$index}}">
<img ng-src="/resize/photo/{{photo.photo_name}}" height="120" width="120"/>
</a>
</div>
</div>
<div ng-repeat-end=""><hz-photo-popup></hz-photo-popup></div>
</div>
hzPhotoDirective.js
(function () {
'use strict';
angular
.module("AppWhizbite")
.directive("hzPhotoPopup", ["$rootScope", "$compile", "HzPhotoService", function ($rootScope, $compile, HzPhotoService) {
var magnificMarkup = "\n\
<form ng-controller=\"PhotoCtrl as Photo\" class=\"white-popup-block popMarkup ng-pristine ng-valid ng-scope\" id=\"dataPopup\" >\n\
<div class=\"popup_heading\">Photo</div>\n\
<div id=\"img_center\">\n\
<img style=\"width:100%\" src=\"\" id=\"img_center_content\" class=\"mfp-imageScale\">\n\
</div>\n\
<div class=\"popup_main\">\n\
<div class=\"popup_left photo_popup_left\">\n\
<div class=\"popup_raw1\">\n\
Edit description\n\
<div class=\"mfp-imageDescription\" style=\"cursor:pointer;\" ng-click=\"doEditDescription()\"></div>\n\
<textarea class=\"submitByEnter commentarea mfp-imageDescription\" placeholder=\"Edit description\" style=\"height: 76px;display:none;\"></textarea>\n\
</div>\n\
</div>\n\
</div>\n\
<div class=\"video_main\">\n\
</div>\n\
<button class=\"mfp-close\" type=\"button\" title=\"Close (Esc)\">×</button>\n\
</form>";
return {
restrict: "AE",
replace: false,
scope: true,
compile: function (scope, element) {
return{
pre: function (scope, element, attrs) {
if (scope.$last) {
// Iterate through all thumbnails class to bind magnific popup plugins
angular.forEach(angular.element(".gallery > .imgWrapper > a"), function (val, key) {
angular.element(".popup-link").eq(key).magnificPopup({
key: 'my-popup',
//items: arrData, // Array of media details
items: $rootScope.arrData, // Array of media details
index: key, // Index of media ref: data-index
type: 'inline',
verticalFit: true, // Fits image in area vertically
inline: {
// Magnific popup custom markup to show media (photo) gallery
markup: $compile(magnificMarkup)(scope)
},
gallery: {
enabled: true
},
callbacks: {
open: function () {
console.log("open called");
},
change: function () {
console.log("cahnge callaed");
},
markupParse: function (template, values, item) {
// optionally apply your own logic - modify "template" element based on data in "values"
// console.log('Parsing:', template, values, item);
console.log("markup parse called");
},
elementParse: function (item) {
console.log("element parse called");
}
}
});
});
}
}
}
},
link: function (scope, element, attrs) {
console.log("link method called");
}
}
}]);
}());
After R&D I crack the issue.
Magnific Popup callbacks objects have markupParse() method. It calls in every action of popup, so I put my angular js template $compile in markupParse method and it works fine.
It may different as per conditions or situations, but almost in all conditions it works finally fine.
Code:
inline: {
// Magnific popup custom markup to show media (photo) gallery
markup: magnificMarkup
},
callbacks:{
markupParse: function (template, values, item) {
$compile(template)(scope);
}
}
In the markupParse method having 3 parameters:
template : template holds actual HTML template which use in popup.
values: value holds current indexed value from arrData
item: item hold current item object.

Add dynamic angular attributes to dom element

I have an ApplicationController that runs over my dynamic controller
This Application controller has an array that are my App-bar actions.
Well, every dynamic controller i have inherit the ability to change this array, once its on $scope.headers.actions;
What I'm trying to do right now is to create a directive where i'll be able to add angular attributes (ng-class, ng-if, etc...) dynamically where this attributes definition will come from $scope.headers.actions[...].attributes
Now my directive is:
app.directive('ngDynamicAttrs', ['$compile',function ($compile) {
return {
scope: { list: '=ngDynamicAttrs' },
//priority: 1001,
//terminal: true,
link: function (scope, elem, attrs) {
for (attr in scope.list) {
attrs.$set(attr, scope.list[attr]);
//elem[0].setAttribute(attr, scope.list[attr]);
//elem.attr(attr, scope.list[attr]);
}
$compile(elem)(scope);
}
};
}]);
My html is:
<ul class="actions">
<li class="action" ng-repeat="action in header.actions.pool" ng-click="action.events.click()" ng-dynamic-attrs="action.attributes" id="{{action.id}}">
<i ng-if="action.icon" class="icon fa {{action.icon}}"></i>
{{action.name}}
</li>
</ul>
And my action object is :
$scope.header = {
actions: {
pool: [],
clear: function (actions) {
$scope.header.actions.pool = [];
},
set: function (actions) {
$scope.header.actions.clear();
for (i in actions) {
$scope.header.actions.add(actions[i].id, actions[i].name, actions[i].icon, actions[i].events, actions[i].items, actions[i].attributes)
}
},
add: function (id, name, icon, events, items, attributes) {
$scope.header.actions.pool.push($scope.header.actions.create(id, name, icon, events, items, attributes));
},
remove: function (id) {
for (i in $scope.header.actions.pool) {
if ($scope.header.actions.pool[i].id == id) delete $scope.header.actions.pool[i];
}
},
create: function (id, name, icon, events, items, attributes) {
return { id: id, name: name, icon: icon, events: events, items: items, attributes: attributes };
}
}
}
Note: I'm not even considering the events right here because it's not a big deal once i can easily use normal dom events.

Create Hoverable popover using angular-ui-bootstrap

I have the following code for creating a popover in my template file:
<span class="icon-globe visibility"
id="visibilityFor{{post.metaData.assetId}}"
popover="{{post.visibilityListStr}}"
popover-placement="right"
popover-trigger="mouseenter"
popover-popup-delay="50"
visibility>
</span>
I have a few clickable links on the popover. But the problem is I'm not able to hover on the popover created. I referred to the link http://jsfiddle.net/xZxkq/
and tried to create a directive viz. 'visibility' for this purpose.
Here is the code:
myAppModule.directive("visibility", function ($timeout,$rootScope) {
return {
controller: function ($scope, $element) {
$scope.attachEvents = function (element) {
$('.popover').on('mouseenter', function () {
$rootScope.insidePopover = true;
});
$('.popover').on('mouseleave', function () {
$rootScope.insidePopover = false;
$(element).popover('hide');
});
}
},
link: function (scope, element, attrs) {
$rootScope.insidePopover = false;
element.bind('mouseenter', function (e) {
$timeout(function () {
if (!$rootScope.insidePopover) {
element.popover('show');
attachEvents(element);
}
}, 200);
});
element.bind('mouseout', function (e) {
$timeout(function () {
if (!$rootScope.insidePopover) {
element.popover('show');
attachEvents(element);
}
}, 200);
});
}
}
});
But I get an exception for 'element.popover' since it is undefined. Please point as to what I'm doing wrong and how can I show/hide the angular ui popover from the directive. I am using angular ui bootstrap JS file.
I have solved it in a very cleaned way and thought to share it:
.popover is being created not as a child of the uib-popover
so the idea is to wrap uib-popover with a parent and to control show&hide on hovering the parent.
.popover and uib-popover are children of this parent
so just left to set popover-trigger=none and you have what you are wishing for.
I created a plunk example:
<span ng-init="popoverOpened=false" ng-mouseover="popoverOpened=true" ng-mouseleave="popoverOpened=false">
<button class="btn btn-default" uib-popover-html="htmlPopover"
popover-trigger="none" popover-placement="bottom-left" popover-is-open="popoverOpened" >
<span>hover me</span>
</button>
</span>
enjoy.
I don't know if this is relevant to the OP anymore, but I've had the same problem and fortunately I managed to solve it.
Undefined error
First thing first, the undefined error you are getting might be (at least in my case) because you are using the development version of ui-bootstrap. In my case I got this error when trying to bind element.popover. After adding the minified version of the library the error went away.
Keep the popover open when hovering over it
To do this I have created a custom directive that makes use of the popover from the ui-bootstrap library.
Directive
app.directive('hoverPopover', function ($compile, $templateCache, $timeout, $rootScope) {
var getTemplate = function (contentType) {
return $templateCache.get('popoverTemplate.html');
};
return {
restrict: 'A',
link: function (scope, element, attrs) {
var content = getTemplate();
$rootScope.insidePopover = false;
$(element).popover({
content: content,
placement: 'top',
html: true
});
$(element).bind('mouseenter', function (e) {
$timeout(function () {
if (!$rootScope.insidePopover) {
$(element).popover('show');
scope.attachEvents(element);
}
}, 200);
});
$(element).bind('mouseleave', function (e) {
$timeout(function () {
if (!$rootScope.insidePopover)
$(element).popover('hide');
}, 400);
});
},
controller: function ($scope, $element) {
$scope.attachEvents = function (element) {
$('.popover').on('mouseenter', function () {
$rootScope.insidePopover = true;
});
$('.popover').on('mouseleave', function () {
$rootScope.insidePopover = false;
$(element).popover('hide');
});
}
}
};
});
This directive also accepts a custom template for the popover, so you are not limited to just title and some text in it. You can create your own html template and feed it to the control.
Usage
<a href="#" hover-popover>Click here</a>
Hopes this helps someone else in the future :)
Edit
As requested, here is a Fiddle link. It lacks the styling, but it should demonstrate the way it works.
There I spend 1 day and finally get solution.
<button uib-popover="{{dynamicPopover.content}}"
popover-trigger="outsideClick" popover-is-open="popoverIsOpen"
ng-mouseenter="popoverIsOpen = !popoverIsOpen"
popover-title="{{dynamicPopover.title}}" type="button" class="btn btn-default">Dynamic Popover</button>
Please check
Plunkeer Link
Check only Dynamic Popover button code
Thanks,
I think Cosmin has the hoverable popover right, but it does seem to be using the Twitter Bootstrap popover method. The idea is to have this hoverable popover implemented only with AngularJS and one of the Bootstrap wrappers for AngularJS, which are UI Bootstrap or AngularStrap.
So I have put together an implementation which uses only AngularStrap:
myApp.directive('hoverablePopover', function ($rootScope, $timeout, $popover) {
return {
restrict: "A",
link: function (scope, element, attrs) {
element.bind('mouseenter', function (e) {
$timeout(function () {
if (!scope.insidePopover) {
scope.popover.show();
scope.attachEventsToPopoverContent();
}
}, 200);
});
element.bind('mouseout', function (e) {
$timeout(function () {
if (!scope.insidePopover) {
scope.popover.hide();
}
}, 400);
});
},
controller: function ($scope, $element, $attrs) {
//The $attrs will server as the options to the $popover.
//We also need to pass the scope so that scope expressions are supported in the popover attributes
//like title and content.
$attrs.scope = $scope;
var popover = $popover($element, $attrs);
$scope.popover = popover;
$scope.insidePopover = false;
$scope.attachEventsToPopoverContent = function () {
$($scope.popover.$element).on('mouseenter', function () {
$scope.insidePopover = true;
});
$($scope.popover.$element).on('mouseleave', function () {
$scope.insidePopover = false;
$scope.popover.hide();
});
};
}
};
});
When you have a popover element, you need to take into account that you have the element that triggers the popover and you also have the element with the actual popover content.
The idea is to keep the popover open when you mouse over the element with the actual popover content. In the case of my directive, the link function takes care of the element that triggers the popover and attaches the mouseenter/mouseout event handlers.
The controller takes care of setting the scope and the popover itself via the AngularStrap $popover service. The controller adds the popover object returned by the AngularStrap service on the scope so that it is available in the link function. It also adds a method attachEventsToPopoverContent, which attaches the mouseenter/mouseout events to the element with the popover content.
The usage of this directive is like this:
<a title="Popover Title" data-placement="left" data-trigger="manual" data-content="{{someScopeObject}}" content-template="idOfTemplateInTemplateCache" hoverablePopover="">
You have to put the trigger in single quotes, because, reasons:
<button uib-popover="I appeared on mouse enter!" popover-trigger="'mouseenter'" type="button" class="btn btn-default">Mouseenter</button>
demo:
https://jsbin.com/fuwarekeza/1/edit?html,output
directive:
myAppModule.directive('popoverHoverable', ['$timeout', '$document', function ($timeout, $document) {
return {
restrict: 'A',
scope: {
popoverHoverable: '=',
popoverIsOpen: '='
},
link: function(scope, element, attrs) {
scope.insidePopover = false;
scope.$watch('insidePopover', function (insidePopover) {
togglePopover(insidePopover);
})
scope.$watch('popoverIsOpen', function (popoverIsOpen) {
scope.insidePopover = popoverIsOpen;
})
function togglePopover (isInsidePopover) {
$timeout.cancel(togglePopover.$timer);
togglePopover.$timer = $timeout(function () {
if (isInsidePopover) {
showPopover();
} else {
hidePopover();
}
}, 100)
}
function showPopover () {
if (scope.popoverIsOpen) {
return;
}
$(element[0]).click();
}
function hidePopover () {
scope.popoverIsOpen = false;
}
$(document).bind('mouseover', function (e) {
var target = e.target;
if (inside(target)) {
scope.insidePopover = true;
scope.$digest();
}
})
$(document).bind('mouseout', function (e) {
var target = e.target;
if (inside(target)) {
scope.insidePopover = false;
scope.$digest();
}
})
scope.$on('$destroy', function () {
$(document).unbind('mouseenter');
$(document).unbind('mouseout');
})
function inside (target) {
return insideTrigger(target) || insidePopover(target);
}
function insideTrigger (target) {
return element[0].contains(target);
}
function insidePopover (target) {
var isIn = false;
var popovers = $('.popover-inner');
for (var i = 0, len = popovers.length; i < len; i++) {
if (popovers[i].contains(target)) {
isIn = true;
break;
}
}
return isIn;
}
}
}
}]);
html:
<span class="icon-globe visibility"
id="visibilityFor{{post.metaData.assetId}}"
popover="{{post.visibilityListStr}}"
popover-is-open="{{post.$open}}"
popover-trigger="click"
popover-hoverable="true"
visibility>
</span>
html
<span class="icon-globe" id="visibilityFor" popover="hello how are you"
popover-placement="right" popover-trigger="mouseenter"
popover-popup-delay="50" viz>
</span>
directive
myAppModule.directive('viz', function ($rootScope,$timeout){
return{
restrict:"A",
link: function (scope, element, attrs) {
$rootScope.insidePopover = false;
element.bind('mouseenter', function (e) {
$timeout(function () {
if (!$rootScope.insidePopover) {
element.popover('show');
// attachEvents(element);
}
}, 200);
});
element.bind('mouseout', function (e) {
$timeout(function () {
if (!$rootScope.insidePopover) {
element.popover('show');
// attachEvents(element);
}
}, 200);
});
}
}
});
Note : - Don't forget to include angular-strap after jQuery.js & angular.js
This feature was added in Angular UI Bootstrap 0.14.0 and is documented here. Disable the triggers and use the popover-is-open property to manually dictate the opened/closed state.
What I did that gets my by in 0.13.X is to set the element to be hoverable to a <button> and then set the popover-trigger="focus". Then style the button how you wish, and focus the button by clicking it. You can hover in the popover and click a link, all I need to do.
Easiest way to have a mouse-event using uib-popover
Look at the below working example !
You need not have a uib-tabset, I faced an issue with uib-tabset and so added that example.
<uib-tabset>
<uib-tab>
<uib-tab-heading>
Tab 1
</uib-tab-heading>
<div>
<span ng-mouseover="popoverIsOpen = true"
ng-mouseleave="popoverIsOpen = false">
<button uib-popover-template="'includeFile.html'"
popover-trigger="outsideClick"
popover-is-open="popoverIsOpen"
popover-placement="right"
type="button" class="btn btn-default">
Dynamic Popover
</button>
</span>
</div>
<p> tab 1</p>
</uib-tab>
<uib-tab>
<uib-tab-heading>
Tab 2
</uib-tab-heading>
<p> tab 2</p>
</uib-tab>
</uib-tabset>
Template: includeFile.html
<div>
<span>This is for tesitng</span>
<strong> www.google.com</strong>
</div>
I needed to do this as well. I have a checkbox in a table cell that can have 3 possible states: Enabled, Disabled, or Special case. The UI spec I have asked for a popover over the box that shows either of those statuses, or for the special case a sentence with a link.
I tried several of these solutions and one of them worked for me, and they all added extra code. After some playing around, I determined I could just add the "popover-popup-close-delay" attribute with a dynamic value. So this works for me:
<td uib-popover-html="getPopoverTxt()" popover-popup-close-delay="{{ele.isspecial ? 2000 : 300}}" popover-popup-delay="300" popover-append-to-body="true" popover-placement="top" popover-trigger="mouseenter">
<input id="issynced{{ele.id}}" name="isChecked" type="checkbox" data-ng-checked="ele.ischecked" data-ng-model="ele.ischecked">
<label for="issynced{{ele.id}}"></label>
</td>
Some context: My table is looping over an array of data objects, so ele is a single object. The getPopoverTxt() is just a simple method in my controller that returns one of the 3 labels I want to show ("Enabled", "Disabled", or "Special Text with HTML"). Its not necessary here, but the takeaway is to get the HTML to work, you have to wrap the string value in $sce.trustAsHtml(), like:
var specialText = $sce.trustAsHtml('Text with a link to contact support');
The rest is all the usual popover and form input settings we normally use. The "popover-popup-close-delay" is the key.

AngularJS dropdown directive hide when clicking outside

I'm trying to create a multiselect dropdown list with checkbox and filter option. I'm trying to get the list hidden with I click outside but could not figure it out how. Appreciate your help.
http://plnkr.co/edit/tw0hLz68O8ueWj7uZ78c
Watch out, your solution (the Plunker provided in the question) doesn't close the popups of other boxes when opening a second popup (on a page with multiple selects).
By clicking on a box to open a new popup the click event will always be stopped. The event will never reach any other opened popup (to close them).
I solved this by removing the event.stopPropagation(); line and matching all child elements of the popup.
The popup will only be closed, if the events element doesn't match any child elements of the popup.
I changed the directive code to the following:
select.html (directive code)
link: function(scope, element, attr){
scope.isPopupVisible = false;
scope.toggleSelect = function(){
scope.isPopupVisible = !scope.isPopupVisible;
}
$(document).bind('click', function(event){
var isClickedElementChildOfPopup = element
.find(event.target)
.length > 0;
if (isClickedElementChildOfPopup)
return;
scope.$apply(function(){
scope.isPopupVisible = false;
});
});
}
I forked your plunker and applied the changes:
Plunker: Hide popup div on click outside
Screenshot:
This is an old post but in case this helps anyone here is a working example of click outside that doesn't rely on anything but angular.
module('clickOutside', []).directive('clickOutside', function ($document) {
return {
restrict: 'A',
scope: {
clickOutside: '&'
},
link: function (scope, el, attr) {
$document.on('click', function (e) {
if (el !== e.target && !el[0].contains(e.target)) {
scope.$apply(function () {
scope.$eval(scope.clickOutside);
});
}
});
}
}
});
OK I had to call $apply() as the event is happening outside angular world (as per doc).
element.bind('click', function(event) {
event.stopPropagation();
});
$document.bind('click', function(){
scope.isVisible = false;
scope.$apply();
});
I realized it by listening for a global click event like so:
.directive('globalEvents', ['News', function(News) {
// Used for global events
return function(scope, element) {
// Listens for a mouse click
// Need to close drop down menus
element.bind('click', function(e) {
News.setClick(e.target);
});
}
}])
The event itself is then broadcasted via a News service
angular.factory('News', ['$rootScope', function($rootScope) {
var news = {};
news.setClick = function( target ) {
this.clickTarget = target;
$rootScope.$broadcast('click');
};
}]);
You can then listen for the broadcast anywhere you need to. Here is an example directive:
.directive('dropdown', ['News', function(News) {
// Drop down menu für the logo button
return {
restrict: 'E',
scope: {},
link: function(scope, element) {
var opened = true;
// Toggles the visibility of the drop down menu
scope.toggle = function() {
element.removeClass(opened ? 'closed' : 'opened');
element.addClass(opened ? 'opened' : 'closed');
};
// Listens for the global click event broad-casted by the News service
scope.$on('click', function() {
if (element.find(News.clickTarget.tagName)[0] !== News.clickTarget) {
scope.toggle(false);
}
});
// Init
scope.toggle();
}
}
}])
I hope it helps!
I was not totally satisfied with the answers provided so I made my own. Improvements:
More defensive updating of the scope. Will check to see if a apply/digest is already in progress
div will also close when the user presses the escape key
window events are unbound when the div is closed (prevents leaks)
window events are unbound when the scope is destroyed (prevents leaks)
function link(scope, $element, attributes, $window) {
var el = $element[0],
$$window = angular.element($window);
function onClick(event) {
console.log('window clicked');
// might need to polyfill node.contains
if (el.contains(event.target)) {
console.log('click inside element');
return;
}
scope.isActive = !scope.isActive;
if (!scope.$$phase) {
scope.$apply();
}
}
function onKeyUp(event) {
if (event.keyCode !== 27) {
return;
}
console.log('escape pressed');
scope.isActive = false;
if (!scope.$$phase) {
scope.$apply();
}
}
function bindCloseHandler() {
console.log('binding window click event');
$$window.on('click', onClick);
$$window.on('keyup', onKeyUp);
}
function unbindCloseHandler() {
console.log('unbinding window click event');
$$window.off('click', onClick);
$$window.off('keyup', onKeyUp);
}
scope.$watch('isActive', function(newValue, oldValue) {
if (newValue) {
bindCloseHandler();
} else {
unbindCloseHandler();
}
});
// prevent leaks - destroy handlers when scope is destroyed
scope.$on('$destroy', function() {
unbindCloseHandler();
});
}
I get $window directly into the link function. However, you do not need to do this exactly to get $window.
function directive($window) {
return {
restrict: 'AE',
link: function(scope, $element, attributes) {
link.call(null, scope, $element, attributes, $window);
}
};
}
There is a cool directive called angular-click-outside. You can use it in your project. It is super simple to use:
https://github.com/IamAdamJowett/angular-click-outside
The answer Danny F posted is awesome and nearly complete, but Thịnh's comment is correct, so here is my modified directive to remove the listeners on the $destroy event of the directive:
const ClickModule = angular
.module('clickOutside', [])
.directive('clickOutside', ['$document', function ($document) {
return {
restrict: 'A',
scope: {
clickOutside: '&'
},
link: function (scope, el, attr) {
const handler = function (e) {
if (el !== e.target && !el[0].contains(e.target)) {
scope.$apply(function () {
console.log("hiiii");
// whatever expression you assign to the click-outside attribute gets executed here
// good for closing dropdowns etc
scope.$eval(scope.clickOutside);
});
}
}
$document.on('click', handler);
scope.$on('$destroy', function() {
$document.off('click', handler);
});
}
}
}]);
If you put a log in the handler method, you will still see it fire when an element has been removed from the DOM. Adding my small change is enough to remove it. Not trying to steal anyone's thunder, but this is a fix to an elegant solution.
Use angular-click-outside
Installation:
bower install angular-click-outside --save
npm install #iamadamjowett/angular-click-outside
yarn add #iamadamjowett/angular-click-outside
Usage:
angular.module('myApp', ['angular-click-outside'])
//in your html
<div class="menu" click-outside="closeThis">
...
</div>
//And then in your controller
$scope.closeThis = function () {
console.log('closing');
}
I found some issues with the implementation in https://github.com/IamAdamJowett/angular-click-outside
If for example the element clicked on is removed from the DOM, the directive above will trigger the logic.
That didn't work for me, since I had some logic in a modal that, after click, removed the element with a ng-if.
I rewrote his implementation. Not battle tested, but seems to be working better (at least in my scenario)
angular
.module('sbs.directives')
.directive('clickOutside', ['$document', '$parse', '$timeout', clickOutside]);
const MAX_RECURSIONS = 400;
function clickOutside($document, $parse, $timeout) {
return {
restrict: 'A',
link: function ($scope, elem, attr) {
// postpone linking to next digest to allow for unique id generation
$timeout(() => {
function runLogicIfClickedElementIsOutside(e) {
// check if our element already hidden and abort if so
if (angular.element(elem).hasClass('ng-hide')) {
return;
}
// if there is no click target, no point going on
if (!e || !e.target) {
return;
}
let clickedElementIsOutsideDirectiveRoot = false;
let hasParent = true;
let recursions = 0;
let compareNode = elem[0].parentNode;
while (
!clickedElementIsOutsideDirectiveRoot &&
hasParent &&
recursions < MAX_RECURSIONS
) {
if (e.target === compareNode) {
clickedElementIsOutsideDirectiveRoot = true;
}
compareNode = compareNode.parentNode;
hasParent = Boolean(compareNode);
recursions++; // just in case to avoid eternal loop
}
if (clickedElementIsOutsideDirectiveRoot) {
$timeout(function () {
const fn = $parse(attr['clickOutside']);
fn($scope, { event: e });
});
}
}
// if the devices has a touchscreen, listen for this event
if (_hasTouch()) {
$document.on('touchstart', function () {
setTimeout(runLogicIfClickedElementIsOutside);
});
}
// still listen for the click event even if there is touch to cater for touchscreen laptops
$document.on('click', runLogicIfClickedElementIsOutside);
// when the scope is destroyed, clean up the documents event handlers as we don't want it hanging around
$scope.$on('$destroy', function () {
if (_hasTouch()) {
$document.off('touchstart', runLogicIfClickedElementIsOutside);
}
$document.off('click', runLogicIfClickedElementIsOutside);
});
});
},
};
}
function _hasTouch() {
// works on most browsers, IE10/11 and Surface
return 'ontouchstart' in window || navigator.maxTouchPoints;
}

AngularJS directive to scroll to a given item

I have a scope variable $scope.first_unread_id which is defined in my controller. In my template, I have:
<div id="items" >
<ul class="standard-list">
<li ng-repeat="item in items" scroll-to-id="first_unread_id">
<span class="content">{{ item.content }}</span>
</li>
</ul>
</div>
and my directive looks like:
angular.module('ScrollToId', []).
directive('scrollToId', function () {
return function (scope, element, attributes) {
var id = scope.$parent[attributes["scrollToId"]];
if (id === scope.item.id) {
setTimeout(function () {
window.scrollTo(0, element[0].offsetTop - 100)
}, 20);
}
}
});
it works, however, two questions:
Is there a better way of getting the "first_unread_id" off the controller scope into the direct than interrogating scope.$parent? This seems a bit 'icky'. I was hoping I could pass that through the view to the direct as a parameter w/o having to repeat that on ever li element.
Is there a better way to avoid the need of the setTimeout() call? Without it, it works sometimes - I imagine due to difference in timing of layout. I understand the syntax I have used is defining a link function - but it isn't clear to me if that is a pre or post-link by default - and if that even matters for my issue.
You shouldn't need the scope.$parent - since it will inherit the value from the parent scope, and when it changes in the parent scope it will be passed down.
The default is a post-link function. Do you have some images or something loading that would make the page layout change shortly after initial load? Have you tried a setTimeout with no time on it, eg setTimeout(function(){})? This would make sure this would go 'one after' everything else is done.
I would also change the logic of your directive a bit to make it more general. I would make it scroll to the element if a given condition is true.
Here are those 3 changes:
html:
<div id="items" >
<ul class="standard-list">
<li ng-repeat="item in items" scroll-if="item.id == first_unread_id">
<span class="content">{{ item.content }}</span>
</li>
</ul>
</div>
JS:
app.directive('scrollIf', function () {
return function (scope, element, attributes) {
setTimeout(function () {
if (scope.$eval(attributes.scrollIf)) {
window.scrollTo(0, element[0].offsetTop - 100)
}
});
}
});
Assuming that the parent element is the one where we scroll, this works for me:
app.directive('scrollIf', function () {
return function(scope, element, attrs) {
scope.$watch(attrs.scrollIf, function(value) {
if (value) {
// Scroll to ad.
var pos = $(element).position().top + $(element).parent().scrollTop();
$(element).parent().animate({
scrollTop : pos
}, 1000);
}
});
}
});
I ended up with the following code (which does not depend on jQ) which also works if the scrolling element is not the window.
app.directive('scrollIf', function () {
var getScrollingParent = function(element) {
element = element.parentElement;
while (element) {
if (element.scrollHeight !== element.clientHeight) {
return element;
}
element = element.parentElement;
}
return null;
};
return function (scope, element, attrs) {
scope.$watch(attrs.scrollIf, function(value) {
if (value) {
var sp = getScrollingParent(element[0]);
var topMargin = parseInt(attrs.scrollMarginTop) || 0;
var bottomMargin = parseInt(attrs.scrollMarginBottom) || 0;
var elemOffset = element[0].offsetTop;
var elemHeight = element[0].clientHeight;
if (elemOffset - topMargin < sp.scrollTop) {
sp.scrollTop = elemOffset - topMargin;
} else if (elemOffset + elemHeight + bottomMargin > sp.scrollTop + sp.clientHeight) {
sp.scrollTop = elemOffset + elemHeight + bottomMargin - sp.clientHeight;
}
}
});
}
});
Same as accepted answer, but uses the javascript built-in method "scrollIntoView":
angular.module('main').directive('scrollIf', function() {
return function(scope, element, attrs) {
scope.$watch(attrs.scrollIf, function(value) {
if (value) {
element[0].scrollIntoView({block: "end", behavior: "smooth"});
}
});
}
});
In combination with UI Router's $uiViewScroll I ended up with the following directive:
app.directive('scrollIf', function ($uiViewScroll) {
return function (scope, element, attrs) {
scope.$watch(attrs.scrollIf, function(value) {
if (value) {
$uiViewScroll(element);
}
});
}
});
In combo with #uri, this works for my dynamic content with ui-router and stateChangeSuccess in .run:
$rootScope.$on('$stateChangeSuccess',function(newRoute, oldRoute){
setTimeout(function () {
var postScroll = $state.params.postTitle;
var element = $('#'+postScroll);
var pos = $(element).position().top - 100 + $(element).parent().scrollTop();
$('body').animate({
scrollTop : pos
}, 1000);
}, 1000);
});
For an answer taking the best of the answers here, in ES6:
File: scroll.directive.js
export default function ScrollDirective() {
return {
restrict: 'A',
scope: {
uiScroll: '='
},
link: link
};
function link($scope, $element) {
setTimeout(() => {
if ($scope.uiScroll) {
$element[0].scrollIntoView({block: "end", behavior: "smooth"});
}
});
}
}
File scroll.module.js
import ScrollDirective from './scroll.directive';
export default angular.module('app.components.scroll', [])
.directive('uiScroll', ScrollDirective);
After importing it in your project, you can use it in the your html:
<div id="items" >
<ul class="standard-list">
<li ng-repeat="item in items" ui-scroll="true">
<span class="content">{{ item.content }}</span>
</li>
</ul>
</div>

Resources