AngularJS Masonry for Dynamically changing heights - javascript

I have divs that expand and contract when clicked on. The Masonry library has worked great for initializing the page. The problem I am experiencing is that with the absolute positioning in place from Masonry and the directive below, when divs expand they overlap with the divs below. I need to have the divs below the expanding div move down to deal with the expansion.
My sources are:
http://masonry.desandro.com/
and
https://github.com/passy/angular-masonry/blob/master/src/angular-masonry.js
/*!
* angular-masonry <%= pkg.version %>
* Pascal Hartig, weluse GmbH, http://weluse.de/
* License: MIT
*/
(function () {
'use strict';
angular.module('wu.masonry', [])
.controller('MasonryCtrl', function controller($scope, $element, $timeout) {
var bricks = {};
var schedule = [];
var destroyed = false;
var self = this;
var timeout = null;
this.preserveOrder = false;
this.loadImages = true;
this.scheduleMasonryOnce = function scheduleMasonryOnce() {
var args = arguments;
var found = schedule.filter(function filterFn(item) {
return item[0] === args[0];
}).length > 0;
if (!found) {
this.scheduleMasonry.apply(null, arguments);
}
};
// Make sure it's only executed once within a reasonable time-frame in
// case multiple elements are removed or added at once.
this.scheduleMasonry = function scheduleMasonry() {
if (timeout) {
$timeout.cancel(timeout);
}
schedule.push([].slice.call(arguments));
timeout = $timeout(function runMasonry() {
if (destroyed) {
return;
}
schedule.forEach(function scheduleForEach(args) {
$element.masonry.apply($element, args);
});
schedule = [];
}, 30);
};
function defaultLoaded($element) {
$element.addClass('loaded');
}
this.appendBrick = function appendBrick(element, id) {
if (destroyed) {
return;
}
function _append() {
if (Object.keys(bricks).length === 0) {
$element.masonry('resize');
}
if (bricks[id] === undefined) {
// Keep track of added elements.
bricks[id] = true;
defaultLoaded(element);
$element.masonry('appended', element, true);
}
}
function _layout() {
// I wanted to make this dynamic but ran into huuuge memory leaks
// that I couldn't fix. If you know how to dynamically add a
// callback so one could say <masonry loaded="callback($element)">
// please submit a pull request!
self.scheduleMasonryOnce('layout');
}
if (!self.loadImages){
_append();
_layout();
} else if (self.preserveOrder) {
_append();
element.imagesLoaded(_layout);
} else {
element.imagesLoaded(function imagesLoaded() {
_append();
_layout();
});
}
};
this.removeBrick = function removeBrick(id, element) {
if (destroyed) {
return;
}
delete bricks[id];
$element.masonry('remove', element);
this.scheduleMasonryOnce('layout');
};
this.destroy = function destroy() {
destroyed = true;
if ($element.data('masonry')) {
// Gently uninitialize if still present
$element.masonry('destroy');
}
$scope.$emit('masonry.destroyed');
bricks = [];
};
this.reload = function reload() {
$element.masonry();
$scope.$emit('masonry.reloaded');
};
}).directive('masonry', function masonryDirective() {
return {
restrict: 'AE',
controller: 'MasonryCtrl',
link: {
pre: function preLink(scope, element, attrs, ctrl) {
var attrOptions = scope.$eval(attrs.masonry || attrs.masonryOptions);
var options = angular.extend({
itemSelector: attrs.itemSelector || '.masonry-brick',
columnWidth: parseInt(attrs.columnWidth, 10) || attrs.columnWidth
}, attrOptions || {});
element.masonry(options);
var loadImages = scope.$eval(attrs.loadImages);
ctrl.loadImages = loadImages !== false;
var preserveOrder = scope.$eval(attrs.preserveOrder);
ctrl.preserveOrder = (preserveOrder !== false && attrs.preserveOrder !== undefined);
scope.$emit('masonry.created', element);
scope.$on('$destroy', ctrl.destroy);
}
}
};
}).directive('masonryBrick', function masonryBrickDirective() {
return {
restrict: 'AC',
require: '^masonry',
scope: true,
link: {
pre: function preLink(scope, element, attrs, ctrl) {
var id = scope.$id, index;
ctrl.appendBrick(element, id);
element.on('$destroy', function () {
ctrl.removeBrick(id, element);
});
scope.$on('masonry.reload', function () {
ctrl.scheduleMasonryOnce('reloadItems');
ctrl.scheduleMasonryOnce('layout');
});
scope.$watch('$index', function () {
if (index !== undefined && index !== scope.$index) {
ctrl.scheduleMasonryOnce('reloadItems');
ctrl.scheduleMasonryOnce('layout');
}
index = scope.$index;
});
}
}
};
});
}());

Like with many non-Angular libraries, it appears the answer lies in wrapping the library in an Angular directive.
I haven't tried it out but it appears that is what this person did

You can use angular's $emit, $broadcast, and $on functionality.
Inside your masonry directive link function:
scope.$on('$resizeMasonry', ctrl.scheduleMasonryOnce('layout'));
Inside your masonryBrick directive link function or any other child element:
scope.$emit('$resizeMasonry');
Use $emit to send an event up the scope tree and $broadcast to send an event down the scope tree.

Related

AngularJS directive changing ability to modify scope variable

Here's a plunkr with my problem: http://plnkr.co/edit/Sx830ekQyP7YBqmRB4Nd?p=preview
Click "Open", then click on "5". Notice how it changes to "test"? Now, type something into Body. It'll either say "Say a little more..." or "Now for the title". Either way, click the button again, and notice how it doesn't change to "test"? Why not? If I remove the directive, the button changes to "test" with or without text in the body.
I know this has to do with the scope in the directive, but I don't understand what exactly is wrong. Can you explain? Thanks.
angular.module('plunker', ['ngDialog']).controller('MainCtrl', function($scope, ngDialog) {
//$scope.submitPostValue = "OK";
$scope.submitPost = function() {
$scope.submitPostValue = 'test';
};
$scope.open = function () {
console.log('open');
$scope.submitPostValue = '5';
ngDialog.openConfirm({
template: 'postModal',
showClose: true,
trapFocus: false,
scope: $scope,
}).then(function (success) {
}, function (error) {
});
};
}).directive('bodyValidator', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
function customValidator(ngModelValue) {
if(ngModelValue.length > 0){
if(ngModelValue.length < 10) {
scope.submitPostValue = "Say a little more...";
scope.bodyValid = false;
}
else {
scope.bodyValid = true;
if(scope.titleValid)
scope.submitPostValue = "Submit";
else
scope.submitPostValue = "Now for the title..."
}
}
else {
scope.submitPostValue = "Enter a body...";
scope.bodyValid = false;
}
return ngModelValue;
}
ctrl.$parsers.push(customValidator);
}
};
});
Try to wrap all your variables into an object.
Define $scope.obj = {}; first and change all your scope.submitPostValue to $scope.obj.submitPostValue. In your HTML, change ng-value='submitPostValue' to ng-value=obj.submitPostValue.

Update event listeners when page switches

I'm in a bit of a predicament, because I need to somehow update event listeners, when the page changes using ajax. I have a specific element that I need to update based on what page the ajax call injects. Here's my issue:
I have this slider control constructor:
UI.CONTROLS.SLIDER = function (select, action, actionWhenActive, actionWhenSet) {
'use strict';
var self = this;
this.action = action;
this.select = select;
this.area = select.find($('area-'));
this.fill = select.find($('fill-'));
this.value = 0;
this.active = false;
this.actionWhenActive = actionWhenActive;
this.actionWhenSet = actionWhenSet;
function eventlisteners(self) {
$(document).on('mousemove', function (event) {
self.move(event, self);
});
$(document).on('mouseup', function (event) {
self.drop(event, self);
});
self.area.on('mousedown', function (event) {
self.grab(event, self);
});
}
eventlisteners(self);
this.reselect = function (element) {
self.area = element.find($('area-'));
self.fill = element.find($('fill-'));
eventlisteners(self);
};
};
UI.CONTROLS.SLIDER.prototype = {
action: this.action,
width: function () {
'use strict';
var calcWidth = ((this.value * 100) + '%');
this.fill.width(calcWidth);
},
update: function (event, self) {
'use strict';
if (this.actionWhenActive === true) {
this.action();
}
var direction, percent, container, area;
direction = event.pageX - this.area.offset().left;
percent = Math.min(Math.max(direction / this.area.width(), 0), 1.0);
this.value = percent;
this.width();
},
move: function (event, self) {
'use strict';
if (this.active === true) {
this.update(event);
}
},
grab: function (event, self) {
'use strict';
this.active = true;
self.update(event);
event.preventDefault();
},
drop: function (event, self) {
'use strict';
if (this.active === true) {
this.active = false;
this.action();
}
},
setValue: function (value) {
'use strict';
if (this.active === false) {
this.value = value;
this.width();
if (this.actionWhenSet === true) {
this.action();
}
}
}
};
This can create new sliders based on the container (select) specified. In my website, I have an audio player. So using ajax you can navigate while this audio player plays. I have two states, viewing a track, and not viewing a track. When you're not viewing the track that is playing, a transport bar will pop down from the header containing the scrubber (slider control), this scrubber is also inside the track view (viewing the track) page.
This code checks if you're viewing the track that is playing. audioFromView gets updated on the ajax calls, it basically replaces it with what track you're viewing. It then compares it with audioCurrent which is the track currently playing, UI.PAGE.TYPE is what type of page you're viewing, in this instance a track:
var audioViewIsCurrent = function () {
'use strict';
if (audioCurrent.src === audioFromView.src && UI.PAGE.TYPE === 'track') {
return true;
} else {
return false;
}
};
So this code then updates the scrubber based on the above code's output (audioElementTrackView is the scrubber inside the track page, and audioElementTransport is the scrubber inside the transport panel):
var audioScrubber = {
element: {},
active: false,
action: function () {
'use strict';
audioScrubber.active = this.active;
var time = audioSource.duration * this.value;
if (this.active === false) {
audioCurrent.time(this.value * duration);
}
},
set: function () {
'use strict';
var container, slider;
if (audioElementTrackView.length === 1) {
container = audioElementTrackView.find(audioElementScrubber);
} else {
container = audioElementTransport.find(audioElementScrubber);
}
this.element = new UI.CONTROLS.SLIDER(container, this.action, true);
},
reselect: function () {
if (audioElementTrackView.length === 1) {
container = audioElementTrackView.find(audioElementScrubber);
} else {
container = audioElementTransport.find(audioElementScrubber);
}
this.element.reselect(container)
}
};
audioScrubber.reselect()
So this works fine with how I'm currently doing it, HOWEVER since I am adding new event listeners everytime I update my scrubber object (inside the ajax call) in order to keep the scrubber working I am also piling them up, making the old event listeners take up space and RAM eventually making the site slow down to a halt (if you navigate enough)
I tested this using console.log on mouseup, everytime I switched page, it would log it twice, and then thrice and so on.
How can I avoid this?
You can delegate events to the nearest static ancestor, so you don't need to rebind them everyime.
Read this article
https://davidwalsh.name/event-delegate

$scope.$watch only triggered once

I've set the following watcher in my controller:
var embeds = {twitter: false, facebook: false};
$scope.$watch(embeds, function(newVal, oldVal) {
if(embeds.twitter && embeds.facebook) $scope.loading = appLoader.off();
});
This should fire when embeds changes. I have the following functions that check if all my embedded Tweets and Facebook posts have loaded for the page. When all Tweets or Facebook posts are loaded, it updates embeds within a $timeout block in order to trigger a digest cycle.
checkFBInit();
twttr.ready(function(twttr) {
twttr.events.bind('loaded', function(event) {
$timeout(function() {
embeds.twitter = true;
});
});
});
function checkFBInit() {
// Ensure FB.init has been called before attempting to subscribe to event
var fbTrys = 0;
function init() {
fbTrys++;
if (fbTrys >= 60) {
return;
} else if (typeof(FB) !== 'undefined') {
fbTrys = 60;
FB.Event.subscribe('xfbml.render', function() {
$timeout(function() {
embeds.facebook = true;
});
});
return;
} else {
init();
};
};
init();
};
The problem I'm having is that my watcher only fires once when I set it. I've tried binding embeds to $scope and/or watching embeds.twitter and embeds.facebook but the watcher only ever fires once.
Use:
$scope.embeds = {twitter: false, facebook: false};
$scope.$watch('embeds', function(newVal, oldVal) {
if ($scope.embeds.twitter && $scope.embeds.facebook) {
$scope.loading = appLoader.off();
}
}, true);
See https://docs.angularjs.org/api/ng/type/$rootScope.Scope. First argument must be string or function which return the name of param.

Angular 2 way binding in video play event doesn't work

My 2 way bidning doesn't work, it works if i call the vm.Play() function directly but when it gets called from the video play event then it doesn't work. Does anyone know why?
function VideoEventStats() {
var directive = {
restrict: "A",
replace: false,
scope: {
videoEventStats: "="
},
controller: controllerFunction,
controllerAs: "vm",
bindToController: true
};
controllerFunction.$inject = ["$element"];
function controllerFunction($element) {
var vm = this;
vm.Play = Play;
if($element.context.tagName === "VIDEO") {
angular.element($element).on('play', vm.Play);
$element.context.onended = function() {
console.log('ended..');
};
}
else {
console.warn('This element is not a video element');
}
function Play() {
vm.videoEventStats.CurrentUserHasSeen = true;
}
}
return directive;
}
Add the vm.videoEventStats.CurrentUserHasSeen = true; inside of a $timeout made the trick...
function Play() { $timeout(function() { vm.videoEventStats.CurrentUserHasSeen = true; }, 0); }

kendoui angular grid selection event

I am trying to handle a selection event from a KendoUI Grid in AngularJS.
I have got my code working as per below. However it feels like a really nasty way of having to get the data for the selected row. Especially using _data. Is there a better way of doing this? Have I got the wrong approach?
<div kendo-grid k-data-source="recipes" k-selectable="true" k-sortable="true" k-pageable="{'refresh': true, 'pageSizes': true}"
k-columns='[{field: "name", title: "Name", filterable: false, sortable: true},
{field: "style", title: "Style", filterable: true, sortable: true}]' k-on-change="onSelection(kendoEvent)">
</div>
$scope.onSelection = function(e) {
console.log(e.sender._data[0].id);
}
please try the following:
$scope.onSelection = function(kendoEvent) {
var grid = kendoEvent.sender;
var selectedData = grid.dataItem(grid.select());
console.log(selectedData.id);
}
Joining the party rather late, there is a direct way to do it without reaching for the grid object:
on the markup:
k-on-change="onSelection(data)"
in the code:
$scope.onSelection = function(data) {
// no need to reach the for the sender
}
note that you may still send selected, dataItem, kendoEvent or columns if needed.
consult this link for more details.
Directive for two-way binding to selected row. Should be put on the same element
as kendo-grid directive.
Typescript version:
interface KendoGridSelectedRowsScope extends ng.IScope {
row: any[];
}
// Directive is registered as gridSelectedRow
export function kendoGridSelectedRowsDirective(): ng.IDirective {
return {
link($scope: KendoGridSelectedRowsScope, element: ng.IAugmentedJQuery) {
var unregister = $scope.$parent.$on("kendoWidgetCreated", (event, grid) => {
if (unregister)
unregister();
// Set selected rows on selection
grid.bind("change", function (e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
selectedDataItems.push(dataItem);
}
if ($scope.row != selectedDataItems[0]) {
$scope.row = selectedDataItems[0];
$scope.$root.$$phase || $scope.$root.$digest();
}
});
// Reset selection on page change
grid.bind("dataBound", () => {
$scope.row = null;
$scope.$root.$$phase || $scope.$root.$digest();
});
$scope.$watch(
() => $scope.row,
(newValue, oldValue) => {
if (newValue !== undefined && newValue != oldValue) {
if (newValue == null)
grid.clearSelection();
else {
var index = grid.dataSource.indexOf(newValue);
if (index >= 0)
grid.select(grid.element.find("tr:eq(" + (index + 1) + ")"));
else
grid.clearSelection();
}
}
});
});
},
scope: {
row: "=gridSelectedRow"
}
};
}
Javascript version
function kendoGridSelectedRowsDirective() {
return {
link: function ($scope, element) {
var unregister = $scope.$parent.$on("kendoWidgetCreated", function (event, grid) {
if (unregister)
unregister();
// Set selected rows on selection
grid.bind("change", function (e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
selectedDataItems.push(dataItem);
}
if ($scope.row != selectedDataItems[0]) {
$scope.row = selectedDataItems[0];
$scope.$root.$$phase || $scope.$root.$digest();
}
});
// Reset selection on page change
grid.bind("dataBound", function () {
$scope.row = null;
$scope.$root.$$phase || $scope.$root.$digest();
});
$scope.$watch(function () { return $scope.row; }, function (newValue, oldValue) {
if (newValue !== undefined && newValue != oldValue) {
if (newValue == null)
grid.clearSelection();
else {
var index = grid.dataSource.indexOf(newValue);
if (index >= 0)
grid.select(grid.element.find("tr:eq(" + (index + 1) + ")"));
else
grid.clearSelection();
}
}
});
});
},
scope: {
row: "=gridSelectedRow"
}
};
}
A quick example of how to do this with an angular directive.
Note here that I'm getting the reference to the underlying kendo grid through the click event and the DOM handle.
//this is a custom directive to bind a kendo grid's row selection to a model
var lgSelectedRow = MainController.directive('lgSelectedRow', function () {
return {
scope: {
//optional isolate scope aka one way binding
rowData: "=?"
},
link: function (scope, element, attributes) {
//binds the click event and the row data of the selected grid to our isolate scope
element.bind("click", function(e) {
scope.$apply(function () {
//get the grid from the click handler in the DOM
var grid = $(e.target).closest("div").parent().data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
scope.rowData = selectedData;
});
});
}
};
});
I would suggest to use like this, I was also getting undefined when I upgraded my application from angular 7 to 15. Now I get event details like this
public selectedRowChangeAction(event:any): void {
console.log(event.selectedRows[0].dataItem.Id); }
event has selected Row at its 0 index and you can have dataItem as first object and then you can have all object details whatever you have for example Id, Name,Product details whatever you want to select, Something like you can see in picture

Categories

Resources