Capturing AngularJS Carousel Slide Change Event [duplicate] - angularjs

I'm using Angular-UI's carousel and I need to tell my google charts to redraw after they have slid into view. In spite of what I've read, I can't seem to hook into the event.
See my attempt:
http://plnkr.co/edit/Dt0wdzeimBcDlOONRiJJ?p=preview
HTML:
<carousel id="myC" interval="myInterval">
<slide ng-repeat="slide in slides" active="slide.active">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<p>{{slide.text}}</p>
</div>
</slide>
</carousel>
On document load:
$('#myC').live('slid.bs.carousel', function (event) { console.log("slid"); } );
It should work something like this:
http://jsfiddle.net/9fwuq/ - non-angular-ui carousel
Perhaps there is a more Angular way to hook into the fact that my chart has slid into view?

There are 3 ways I can think of and that depends of your requirement.
Please see http://plnkr.co/edit/FnI8ZX4UQYS9mDUlrf6o?p=preview for examples.
use $scope.$watch for an individual slide to check if it is become active.
$scope.$watch('slides[0].active', function (active) {
if (active) {
console.log('slide 0 is active');
}
});
use $scope.$watch with custom function to find an active slide.
$scope.$watch(function () {
for (var i = 0; i < slides.length; i++) {
if (slides[i].active) {
return slides[i];
}
}
}, function (currentSlide, previousSlide) {
if (currentSlide !== previousSlide) {
console.log('currentSlide:', currentSlide);
}
});
use a custom directive to intercept select() function of the carousel directive.
.directive('onCarouselChange', function ($parse) {
return {
require: 'carousel',
link: function (scope, element, attrs, carouselCtrl) {
var fn = $parse(attrs.onCarouselChange);
var origSelect = carouselCtrl.select;
carouselCtrl.select = function (nextSlide, direction) {
if (nextSlide !== this.currentSlide) {
fn(scope, {
nextSlide: nextSlide,
direction: direction,
});
}
return origSelect.apply(this, arguments);
};
}
};
});
and use it like this:
$scope.onSlideChanged = function (nextSlide, direction) {
console.log('onSlideChanged:', direction, nextSlide);
};
and in html template:
<carousel interval="myInterval" on-carousel-change="onSlideChanged(nextSlide, direction)">
...
Hope this help : )

AngularUI Bootstrap has changed naming conventions for controllers as thery have prefixed all of their controllers with prefix uib, so below is the updated solution of the original solution provided by runTarm:
Angular:
.directive('onCarouselChange', function($parse) {
return {
require: '^uibCarousel',
link: function(scope, element, attrs, carouselCtrl) {
var fn = $parse(attrs.onCarouselChange);
var origSelect = carouselCtrl.select;
carouselCtrl.select = function(nextSlide, direction, nextIndex) {
if (nextSlide !== this.currentSlide) {
fn(scope, {
nextSlide: nextSlide,
direction: direction,
nextIndex: this.indexOfSlide(nextSlide)
});
}
return origSelect.apply(this, arguments);
};
}
};
});
Angular with TypeScript:
module App.Directive {
export class CarouselChange implements ng.IDirective {
public require: string = '^uibCarousel';
constructor(private $parse: ng.IParseService) { }
public link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: any, carouselCtrl: any) => {
var fn = this.$parse(attributes.carouselChange);
var origSelect = carouselCtrl.select;
carouselCtrl.select = function(nextSlide, direction) {
if (nextSlide !== this.currentSlide) {
fn(scope, {
nextSlide: nextSlide,
direction: direction
});
}
return origSelect.apply(this, arguments);
};
}
static Factory(): ng.IDirectiveFactory {
var directive: ng.IDirectiveFactory = ($parse: ng.IParseService) => new CarouselChange($parse);
directive['$inject'] = ["$parse"];
return directive;
}
}
}
Thanks,

Following the answer given by runTarm If you want to know the index of the next slide, you should add something like this:
.directive('onCarouselChange', function ($parse) {
return {
require: 'carousel',
link: function (scope, element, attrs, carouselCtrl) {
var fn = $parse(attrs.onCarouselChange);
var origSelect = carouselCtrl.select;
carouselCtrl.select = function (nextSlide, direction,nextIndex) {
if (nextSlide !== this.currentSlide) {
fn(scope, {
nextSlide: nextSlide,
direction: direction,
nextIndex:this.indexOfSlide(nextSlide)
});
}
return origSelect.apply(this, arguments);
};
}
};
})
Then, in the controller you just need to do this to catch the new index:
$scope.onSlideChanged = function (nextSlide, direction, nextIndex) {
console.log(nextIndex);
}

I managed to modify runTarm's answer so that it calls the callback once the slide has finished sliding into view (i.e. the sliding animation has finished). Here's my code:
.directive('onCarouselChange', function ($animate, $parse) {
return {
require: 'carousel',
link: function (scope, element, attrs, carouselCtrl) {
var fn = $parse(attrs.onCarouselChange);
var origSelect = carouselCtrl.select;
carouselCtrl.select = function (nextSlide, direction) {
if (nextSlide !== this.currentSlide) {
$animate.on('addClass', nextSlide.$element, function (elem, phase) {
if (phase === 'close') {
fn(scope, {
nextSlide: nextSlide,
direction: direction,
});
$animate.off('addClass', elem);
}
});
}
return origSelect.apply(this, arguments);
};
}
};
});
The secret lies in using $animate's event handler to call our function once the animation is finished.

here's an alternate method that uses controllers, somewhere between runTarm's #2 and #3.
original HTML + a new div:
<carousel id="myC" interval="myInterval">
<slide ng-repeat="slide in slides" active="slide.active">
<div ng-controller="SlideController"> <!-- NEW DIV -->
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<p>{{slide.text}}</p>
</div>
</div>
</slide>
</carousel>
the custom controller:
.controller('SlideController',
function($log, $scope) {
var slide = $scope.slide;
$scope.$watch('slide.active', function(newValue) {
if (newValue) {
$log.info("ACTIVE", slide.id);
}
});
});

And if you just want to start playing a video when the slide comes into view, and pause when it leaves:
JS
{# Uses angular v1.3.20 & angular-ui-bootstrap v0.13.4 Carousel #}
{% addtoblock "js" %}<script type="text/javascript">
angular.module('videoplay', []).directive('videoAutoCtrl', function() {
return {
require: '^carousel',
link: function(scope, element, attrs) {
var video = element[0];
function setstate(visible) {
if(visible) {
video.play();
} else {
video.pause();
}
}
// Because $watch calls $parse on the 1st arg, the property doesn't need to exist on first load
scope.$parent.$watch('active', setstate);
}
};
});
</script>{% endaddtoblock %}
{% addtoblock "ng-requires" %}videoplay{% endaddtoblock %}
NOTE: Has additional bits for Django
HTML:
<carousel interval="15000">
<slide>
<video class="img-responsive-upscale" video-auto-ctrl loop preload="metadata">
<source src=
...

Related

AngularJS - view not updated when directive changes data in service

I'm using a directive to interact with a service and am encountering some trouble with the view showing the latest data.
I setup the following example. You can see that when a controller interacts with the Service, the view will update with the latest data. If you click the directive link, you can see in the console the data was changed but the view is not updated with that data.
http://jsfiddle.net/kisonay/pv8towqc/
What am I missing?
JavaScript:
var app = angular.module('myApp', []);
app.factory('Service', function() {
var Service = {};
Service.data = {};
Service.data.active = false;
Service.data.one = {};
Service.data.many = [];
Service.changeActive = function(state) {
state = state || false;
Service.data.active = state;
};
Service.setOne = function(one) {
Service.data.one = one;
};
Service.setMany = function(many) {
Service.data.many = many;
};
return Service;
});
app.directive('launcher', function(Service) {
return {
restrict: "A",
link: function(scope, elem, attrs) {
elem.bind('click', function(event) {
if (Service.data.active) {
Service.changeActive(false);
} else {
Service.changeActive(true);
}
console.log(Service.data); // shows data changed
});
}
};
});
function Ctrl1($scope, Service) {
$scope.ServiceData = Service.data;
}
function Ctrl2($scope, Service) {
$scope.active = function() {
Service.changeActive(true);
};
$scope.inactive = function() {
Service.changeActive(false);
};
}
HTML
<div ng-controller="Ctrl1">
{{ServiceData}}
</div>
<hr />
<div ng-controller="Ctrl2">
Directive: <a href="#" launcher>Change</a>
<hr /> Controller:
<button ng-click="active()">
Active
</button>
<button ng-click="inactive()">
Inactive
</button>
</div>
Your event listener executes but Angular doesn't know anything about it, so it doesn't know it has to detect changes.
Add scope.$apply(); at the evn of the click listener, and it will work as expected.
app.directive('launcher', function(Service) {
return {
restrict: "A",
link: function(scope, elem, attrs) {
elem.bind('click', function(event) {
scope.$apply(function() {
if (Service.data.active) {
Service.changeActive(false);
} else {
Service.changeActive(true);
}
});
});
}
};
});

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
);
}

Angular sce.trustAsHtml not working

I have this angular controller :
var applicaton = angular.module("appUsed", ['ui.router','ngSanitize'] );
applicaton.controller('gamesController', ['$scope','$http','$sce','$stateParams',function(scope,http,sce,stateParams){
http.get('/'+stateParams.category+'/'+stateParams.id)
.success(function(result){
scope.Game = result.gameDetails;
scope.relatedGames = result.relatedGames;
console.log(scope.Game.title);
console.log(scope.Game.url);
scope.gameUrl = sce.trustAsHtml('<iframe allowfullscreen width="80%" height="600px src="'+scope.Game.url+'"></iframe>');
});
}]);
and this html :
<div class="game_and_description">
<div ng-bind-html="gameUrl"></div>
<h3> Description</h3>
<p> {{Game.description}}</p>
It shows me a white iframe. I searched over the internet and i've done everything right. The modules form angular ng-sanitize is running(called from <script> tag) and i have no error. the console log on scopes works like a charm. Don't know where should i look anymore. Please help.
You need to give a trust to the URL you are using in the iframe, and compile the html:
<div ng-controller="gamesController">
<div bind-html-compile="gameFrame"></div>
</div>
var myApp = angular
.module('appUsed',['ngSanitize'])
.controller('gamesController', ['$scope', '$sce', function (scope, sce) {
scope.Game = {
url: 'https://play.famobi.com/hop-dont-stop/A-DXC93'
};
scope.gameUrl = sce.trustAsResourceUrl(scope.Game.url);
scope.gameFrame = sce.trustAsHtml('<iframe allowfullscreen width="80%" height="600px" ng-src="{{gameUrl}}"></iframe>');
}])
.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value && value.toString());
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);
See https://github.com/incuna/angular-bind-html-compile.
The working fiddle: http://jsfiddle.net/masa671/k2e43nvf/
I had a similar problem. I solved it like this :
my view :
<div ng-bind-html="getDescription()"></div>
my controller :
$scope.getDescription = function () {
if ($scope.description != null && $scope.todo.description.length > 0) {
return $sce.trustAsHtml($scope.description);
} else {
return 'no description.';
}
};

AngularJS binding issues and iteration loops

I have this factory:
.factory('Options', function () {
var getOptions = function () {
var storageData = sessionStorage.siteOptions;
if (storageData !== 'undefined')
return angular.fromJson(storageData);
return {
rotateBackground: false,
enableMetro: true
};
};
var saveOptions = function (options) {
sessionStorage.siteOptions = angular.toJson(options);
}
return {
get: getOptions,
save: saveOptions
};
});
which works fine on my profile page:
.controller('ProfileController', ['Options', function (options) {
var self = this;
self.options = options.get();
self.save = function () {
options.save(self.options);
}
}]);
The html looks like this:
<div class="row" ng-controller="ProfileController as profile">
<div class="large-4 columns">
<h2>Site options</h2>
<form name="optionsForm" ng-submit="profile.save()" role="form">
<div class="row">
<div class="large-12 columns">
<input id="enable-metro" type="checkbox" ng-model="profile.options.enableMetro"><label for="enable-metro">Enable metro design</label>
</div>
<div class="large-12 columns">
<input id="enable-background-rotate" type="checkbox" ng-model="profile.options.rotateBackground"><label for="enable-background-rotate">Enable rotating background</label>
</div>
<div class="large-12 columns">
<button class="button">Save</button>
</div>
</div>
</form>
</div>
</div>
But I have this other page that has a controller that needs to be aware if the options are ever saved. Basically, if saveOptions is ever called, then I need any page that looks at options to be notified.
The reason for this, is for example:
.controller('MetroController', ['Options', function (options) {
scope.options = options.get();
scope.$watch(function () {
return options.get();
}, function () {
scope.options = options.get();
});
}])
// ---
// DIRECTIVES.
// ---
.directive('metro', function () {
return {
restrict: 'A',
controller: 'MetroController',
controllerAs: 'metro',
link: function (scope, element, attr) {
scope.$watch(function () {
return metro.options.enableMetro;
}, function (enableMetro) {
if (enableMetro) {
element.addClass('metro');
} else {
element.removeClass('metro');
}
});
}
}
});
As you can see, this is trying to apply a class based on the enableMetro flag. But when I run this, I get an error about the amount of iterations this has had to loop through.
Can someone help me with this?
I think I have this solved.
I changed my options factory to this:
.factory('Options', function () {
var getOptions = function () {
var storageData = sessionStorage.siteOptions;
if (storageData !== 'undefined')
return angular.fromJson(storageData);
return {
rotateBackground: false,
enableMetro: true
};
};
var saveOptions = function (options) {
sessionStorage.siteOptions = angular.toJson(options);
current = getOptions();
}
var current = getOptions();
return {
current: current,
save: saveOptions
};
});
then in my controllers, I just did this:
.controller('MetroController', ['$scope', 'Options', function ($scope, options) {
var self = this;
self.options = options.current;
$scope.$watch(function () {
return options.current;
}, function () {
self.options = options.current;
});
}])
// ---
// DIRECTIVES.
// ---
.directive('metro', function () {
return {
restrict: 'A',
controller: 'MetroController',
link: function (scope, element, attr, controller) {
scope.$watch(function () {
return controller.options.enableMetro;
}, function (enableMetro) {
if (enableMetro) {
element.addClass('metro');
} else {
element.removeClass('metro');
}
});
}
}
});
and that seems to work fine.

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