update the list using onscroll event - angularjs

<ul>
<li></li>
<li></li>
</ul>
when I scroll to the bottom of the page, I want the page to load <li>info</li>.
$window.onscroll = function($event){
if($window.pageYOffset > [the parent element height]){
//TODO
}
};
So how can I get the parent element height using angular? I try to visit https://docs.angularjs.org/api/ng/service/$window to find the related api but this page didn't list the attr of the $window, by the way, how can I get all attrs of $window in angular.

Try this
$document.on('scroll', function() {
// do your things
console.log($window.scrollY);
// or pass this to the scope
$scope.$apply(function() {
$scope.pixelsScrolled = $window.scrollY;
})
});
I think best way to manage directives
app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= 100) {
scope.boolChangeClass = true;
console.log('Scrolled below header.');
} else {
scope.boolChangeClass = false;
console.log('Header is in view.');
}
scope.$apply();
});
};
});

Related

How to get async html attribut

I have a list of items retreived by an async call and the list is shown with the help of ng-repeat. Since the div container of that list has a fixed height (400px) I want the scrollbar to be at the bottom. And for doing so I need the scrollHeight. But the scrollHeight in postLink is not the final height but the initial height.
Example
ppChat.tpl.html
<!-- Height of "chatroom" is "400px" -->
<div class="chatroom">
<!-- Height of "messages" after all messages have been loaded is "4468px" -->
<div class="messages" ng-repeat="message in chat.messages">
<chat-message data="message"></chat-message>
</div>
</div>
ppChat.js
// [...]
compile: function(element) {
element.addClass('pp-chat');
return function(scope, element, attrs, PpChatController) {
var messagesDiv;
// My idea was to wait until the messages have been loaded...
PpChatController.messages.$loaded(function() {
// ...and then recompile the messages div container
messagesDiv = $compile(element.children()[0])(scope);
// Unfortunately this doesn't work. "messagesDiv[0].scrollHeight" still has its initial height of "400px"
});
}
}
Can someone explain what I missed here?
As required here is a plunk of it
You can get the scrollHeight of the div after the DOM is updated by doing it in the following way.
The below directive sets up a watch on the array i.e. a collection, and uses the $timeout service to wait for the DOM to be updated and then it scrolls to the bottom of the div.
chatDirective.$inject = ['$timeout'];
function chatDirective($timeout) {
return {
require: 'chat',
scope: {
messages: '='
},
templateUrl: 'partials/chat.tpl.html',
bindToController: true,
controllerAs: 'chat',
controller: ChatController,
link: function(scope, element, attrs, ChatController) {
scope.$watchCollection(function () {
return scope.chat.messages;
}, function (newValue, oldValue) {
if (newValue.length) {
$timeout(function () {
var chatBox = document.getElementsByClassName('chat')[0];
console.log(element.children(), chatBox.scrollHeight);
chatBox.scrollTop = chatBox.scrollHeight;
});
}
});
}
};
}
The updated plunker is here.
Also in your Controller you have written as,
var Controller = this;
this.messages = [];
It's better to write in this way, here vm stands for ViewModel
AppController.$inject = ['$timeout'];
function AppController($timeout) {
var vm = this;
vm.messages = [];
$timeout(
function() {
for (var i = 0; i < 100; i++) {
vm.messages.push({
message: getRandomString(),
created: new Date()
});
}
},
3000
);
}

Angularjs: how to position a popup menu (directive - service communication)

I want to connect a popup menu with multiple input elements and show the menu when a new input element is focused. The menu closes on an "outside-of-menu click".
simplified example plknr link / code below.
I'm wondering about what is the most direct way to update the position of the popup menu for this situation. In other words: How to get the info about the newly focused input element back into the directive to make the changes there (position and value of the input element).
In my code I'm storing info about the position on a service (and also the reference to the currently focused input element), but this is not working (the directive does not update without scope.$apply) .
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $document, eventService) {
$("input").on("focus", function(event) {
$scope.$apply(function() {
eventService.register(event.target, $scope);
eventService.positon = $(event.target).position();
$scope.position = eventService.position;
console.log("in", $scope.position);
eventService.addMenu();
});
console.log('from event', $(event.target).position());
});
$("input").on("blur", function() {
console.log('blured');
// eventService.closeList()
});
});
app.directive("myMenu", function($document, eventService, $compile) {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var menu = angular.element('<div id="menu" class="menu">menu {{menuText}}<div>');
$compile(menu)(scope);
eventService.input = $("input").first(); //set the first input
scope.menuText = eventService.input.val();
scope.$watch(function() {
return eventService.input.val();
}, function(newValue, ov) {
scope.menuText = newValue;
});
// $document.off("dialogmutex", closeMenu);
$document.on("dialogmutex", closeMenu);
// close menu on outside click:
$document.on("click", function(event) {
// if the menu or input is clicked dont close it.
if (!((event.target === elem[0]) || event.target === eventService.input[0] || (elem.find(event.target).length > 0))) {
$document.trigger("dialogmutex");
}
});
function addMenu() {
// positioning the menu does not work
var pos = eventService.position;
if (pos) {
elem.css({
top: pos.yPos,
left: pos.xPos,
position: 'absolute'
});
}
console.log("directive position:", pos);
elem.append(menu);
scope.menuText += " x "
}
function closeMenu() {
elem.find("#menu").remove();
}
addMenu(); // open menu on app start
eventService.addMenu = addMenu; // open the menu later from the controller via service
}
};
});
// service used to register a new input element with the directive.
app.service('eventService', function() {
service = {
register: function(el) {
service.input = $(el);
console.log('reg');
service.position = service.input.position();
console.log("on service", service.position)
}
};
return service;
});
Update:
I got it working using ngStyle directive on the container element and a positionCSS Object on the directive scope ,this way I only need to call $scope.$apply once (inside the event handler)
Using id for each input and the using .closest in jQuery should do the trick. You can refer to this link for detailed version.

AngularJS - bind to directive resize

How can i be notified when a directive is resized?
i have tried
element[0].onresize = function() {
console.log(element[0].offsetWidth + " " + element[0].offsetHeight);
}
but its not calling the function
(function() {
'use strict';
// Define the directive on the module.
// Inject the dependencies.
// Point to the directive definition function.
angular.module('app').directive('nvLayout', ['$window', '$compile', layoutDirective]);
function layoutDirective($window, $compile) {
// Usage:
//
// Creates:
//
var directive = {
link: link,
restrict: 'EA',
scope: {
layoutEntries: "=",
selected: "&onSelected"
},
template: "<div></div>",
controller: controller
};
return directive;
function link(scope, element, attrs) {
var elementCol = [];
var onSelectedHandler = scope.selected();
element.on("resize", function () {
console.log("resized.");
});
$(window).on("resize",scope.sizeNotifier);
scope.$on("$destroy", function () {
$(window).off("resize", $scope.sizeNotifier);
});
scope.sizeNotifier = function() {
alert("windows is being resized...");
};
scope.onselected = function(id) {
onSelectedHandler(id);
};
scope.$watch(function () {
return scope.layoutEntries.length;
},
function (value) {
//layout was changed
activateLayout(scope.layoutEntries);
});
function activateLayout(layoutEntries) {
for (var i = 0; i < layoutEntries.length; i++) {
if (elementCol[layoutEntries[i].id]) {
continue;
}
var div = "<nv-single-layout-entry id=slot" + layoutEntries[i].id + " on-selected='onselected' style=\"position:absolute;";
div = div + "top:" + layoutEntries[i].position.top + "%;";
div = div + "left:" + layoutEntries[i].position.left + "%;";
div = div + "height:" + layoutEntries[i].size.height + "%;";
div = div + "width:" + layoutEntries[i].size.width + "%;";
div = div + "\"></nv-single-layout-entry>";
var el = $compile(div)(scope);
element.append(el);
elementCol[layoutEntries[i].id] = 1;
}
};
}
function controller($scope, $element) {
}
}
})();
Use scope.$watch with a custom watch function:
scope.$watch(
function () {
return [element[0].offsetWidth, element[0].offsetHeight].join('x');
},
function (value) {
console.log('directive got resized:', value.split('x'));
}
)
You would typically want to watch the element's offsetWidth and offsetHeight properties. With more recent versions of AngularJS, you can use $scope.$watchGroup in your link function:
app.directive('myDirective', [function() {
function link($scope, element) {
var container = element[0];
$scope.$watchGroup([
function() { return container.offsetWidth; },
function() { return container.offsetHeight; }
], function(values) {
// Handle resize event ...
});
}
// Return directive definition ...
}]);
However, you may find that updates are quite slow when watching the element properties directly in this manner.
To make your directive more responsive, you could moderate the refresh rate by using $interval. Here's an example of a reusable service for watching element sizes at a configurable millisecond rate:
app.factory('sizeWatcher', ['$interval', function($interval) {
return function (element, rate) {
var self = this;
(self.update = function() { self.dimensions = [element.offsetWidth, element.offsetHeight]; })();
self.monitor = $interval(self.update, rate);
self.group = [function() { return self.dimensions[0]; }, function() { return self.dimensions[1]; }];
self.cancel = function() { $interval.cancel(self.monitor); };
};
}]);
A directive using such a service would look something like this:
app.directive('myDirective', ['sizeWatcher', function(sizeWatcher) {
function link($scope, element) {
var container = element[0],
watcher = new sizeWatcher(container, 200);
$scope.$watchGroup(watcher.group, function(values) {
// Handle resize event ...
});
$scope.$on('$destroy', watcher.cancel);
}
// Return directive definition ...
}]);
Note the call to watcher.cancel() in the $scope.$destroy event handler; this ensures that the $interval instance is destroyed when no longer required.
A JSFiddle example can be found here.
Here a sample code of what you need to do:
APP.directive('nvLayout', function ($window) {
return {
template: "<div></div>",
restrict: 'EA',
link: function postLink(scope, element, attrs) {
scope.onResizeFunction = function() {
scope.windowHeight = $window.innerHeight;
scope.windowWidth = $window.innerWidth;
console.log(scope.windowHeight+"-"+scope.windowWidth)
};
// Call to the function when the page is first loaded
scope.onResizeFunction();
angular.element($window).bind('resize', function() {
scope.onResizeFunction();
scope.$apply();
});
}
};
});
The only way you would be able to detect size/position changes on an element using $watch is if you constantly updated your scope using something like $interval or $timeout. While possible, it can become an expensive operation, and really slow your app down.
One way you could detect a change on an element is by calling
requestAnimationFrame.
var previousPosition = element[0].getBoundingClientRect();
onFrame();
function onFrame() {
var currentPosition = element[0].getBoundingClientRect();
if (!angular.equals(previousPosition, currentPosition)) {
resiszeNotifier();
}
previousPosition = currentPosition;
requestAnimationFrame(onFrame);
}
function resiszeNotifier() {
// Notify...
}
Here's a Plunk demonstrating this. As long as you're moving the box around, it will stay red.
http://plnkr.co/edit/qiMJaeipE9DgFsYd0sfr?p=preview
A slight variation on Eliel's answer worked for me. In the directive.js:
$scope.onResizeFunction = function() {
};
// Call to the function when the page is first loaded
$scope.onResizeFunction();
angular.element($(window)).bind('resize', function() {
$scope.onResizeFunction();
$scope.$apply();
});
I call
$(window).resize();
from within my app.js. The directive's d3 chart now resizes to fill the container.
Here is my take on this directive (using Webpack as bundler):
module.exports = (ngModule) ->
ngModule.directive 'onResize', ['Callback', (Callback) ->
restrict: 'A'
scope:
onResize: '#'
onResizeDebounce: '#'
link: (scope, element) ->
container = element[0]
eventName = scope.onResize || 'onResize'
delay = scope.onResizeDebounce || 1000
scope.$watchGroup [
-> container.offsetWidth ,
-> container.offsetHeight
], _.debounce (values) ->
Callback.event(eventName, values)
, delay
]

how to defer a method execution in a directive in angularjs

I'm writing a directive which recives a function as a parameter, the directive executes and run whatever is contained into the function.
the use case is:
the directive contains a link
when the user click the link the method passed as a parameter (from the controller) is executed
when the user hit the click button a spinner will show
the spinner will hide when the execution of the method is finished
my question is how can I defer the execution and bind it to a promise, to hide the spinner after the method execution.
for illustration purposes I have used $timeout that counts from 3 to 1, please take a look to the code I've done so far:
app.directive('toogleTextLink', function($compile,$q) {
return {
restrict: 'AE',
scope: { callback: "&targetMethod" },
template: '<div><a style="cursor: pointer" ><b>{{text}}</b></a>show value= {{show}} <br/><div ng-class="{previewLoader: show}"></div></div>',
link: function (scope, element, attr) {
scope.value = attr.value;
scope.show = false;
scope.$watch('value', function () {
if (scope.value) {
scope.text = "yes";
} else {
scope.text = "no";
}
});
element.bind('click', function () {
scope.show = true;
scope.value = !scope.value;
scope.$digest();
if (scope.callback) {
var deferred = $q.defer(scope.callback());
deferred.promise.then(function () {
scope.show = false;
console.log("then called");
});
}
});
}
};
});
app.controller('myCtrl', function($scope,$timeout,$q) {
$scope.IsFacebookConnected = false;
$scope.countDown = 3;
$scope.authSocial = function(value, socialNetwork) {
switch (socialNetwork) {
case "facebook":
$scope.IsFacebookConnected = !value;
}
runCounter = function() {
$scope.countDown -= 1;
if ( $scope.countDown > 0)
$timeout(runCounter, 1000);
console.log("timer");
};
runCounter();
};
});
this is the plunker as well.
Andy Joslin wrote a "promise tracker" which does exactly what you need. It even has some sugar for $http integration. Basically you add "promises" to it, and it tells you the execution state. You can then bind that execution state to ng-show on something like a loading spinner animation. https://github.com/ajoslin/angular-promise-tracker and here's a demo: http://plnkr.co/edit/3uAe0NdXLz1lCYlhpaMp?p=preview
Your code will look something like:
$scope.tracker = promiseTracker("socialtracker");
$scope.tracker.addPromise(somePromise);
And in your view:
<div ng-show="tracker.active()">Loading...</div>

Accessing hammer event info from Angular directive inside controller

I'm new to Angular, and I'm trying to get the XY coordinates of a tap using angular-hammer.js directives. Here's how the directives are set up:
var hmTouchevents = angular.module('hmTouchevents', []),
hmGestures = ['hmHold:hold',
'hmTap:tap',
'hmDoubletap:doubletap',
'hmDrag:drag',
'hmDragup:dragup',
'hmDragdown:dragdown',
'hmDragleft:dragleft',
'hmDragright:dragright',
'hmSwipe:swipe',
'hmSwipeup:swipeup',
'hmSwipedown:swipedown',
'hmSwipeleft:swipeleft',
'hmSwiperight:swiperight',
'hmTransform:transform',
'hmRotate:rotate',
'hmPinch:pinch',
'hmPinchin:pinchin',
'hmPinchout:pinchout',
'hmTouch:touch',
'hmRelease:release'];
angular.forEach(hmGestures, function(name){
var directive = name.split(':'),
directiveName = directive[0],
eventName = directive[1];
hmTouchevents.directive(directiveName, ["$parse", function($parse) {
return {
scope: true,
link: function(scope, element, attr) {
var fn, opts;
fn = $parse(attr[directiveName]);
opts = $parse(attr["hmOptions"])(scope, {});
scope.hammer = scope.hammer || Hammer(element[0], opts);
return scope.hammer.on(eventName, function(event) {
return scope.$apply(function() {
return fn(scope, {
$event: event
});
});
});
}
};
}
]);
});
My html looks like this:
<div ng-controller="IndexCtrl" >
<div class='tap-area' hm-tap="tap();">
</div>
</div>
My controller looks like this:
App.controller('IndexCtrl', function ($scope, Myapp) {
$scope.tap = function(ev){
//How do I get the event.gesture.center.pageX in here?
};
});
I figured out how to make this work. After return scope.hammer.on(eventName, function(event) { I added scope.event = event; and then in my controller I can get XY coords of a tap by using this.event.center.pageX or this.event.center.pageY.
It was posted long time ago but here is another solution.
Just add $event to your html

Resources