In my Angular app, we have a bootstrap carousel (using bootstrap carousel rather than ui bootstrap carousel for some reasons), items structure as follows
<div class="item" analytics-on analytics-event="IMPRESSIONS" analytics-category="{{--}}" analytics-label="{{--}}" ng-repeat="banner in vm.bannerList">
<a ng-href="{{--}}" analytics-on analytics-event="CLICK" analytics-category="{{--}}" analytics-label="{{--}}">
<div class="fill" style="background-image: url({{--}});"></div>
</a>
</div>
The click event working fine. But how to track the IMPRESSIONS. The impression event need to trigger when a carousel item becomes active.
I tried to watch the 'active' class using a custom directive but the watch only worked on load time.
Tried and succeeded,
Following custom directive did the job.
//ng-track-carousel-impressions
angular.module('app').directive('ngTrackCarouselImpressions', ['$analytics',function (analytics) {
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
// create an observer instance
var observer = new MutationObserver(function (mutations) {
scope.$apply(function () {
if (element.hasClass('active')) {
//console.log(element.attr('analytics-label'));
// emit event track (with category and label properties for GA)
analytics.eventTrack(element.attr('analytics-event'), {
category: element.attr('analytics-category'), label: element.attr('analytics-label')
});
}
});
});
// configuration of the observer:
var config = {
attributes: true
};
// pass in the target node, as well as the observer options
var node = element.get(0);
observer.observe(node, config);
}
}
}]);
Usage
<div class="item" analytics-event="IMPRESSIONS" analytics-category="{{--}}" analytics-label="{{--}}" ng-repeat="banner in vm.bannerList" ng-track-carousel-impressions>
<a ng-href="{{--}}" analytics-on analytics-event="CLICK" analytics-category="{{--}}" analytics-label="{{--}}">
<div class="fill" style="background-image: url({{--}});"></div>
</a>
</div>
Related
I'm using the Siema carousel on my site with Zepto. I'd like to be able to indicate what slide the user is currently on. How do I do this if there is only an onChange event available?
HTML
<section class="images">
<img/>
<img/>
</section>
<section class="indicators">
<span class="active"></span>
<span></span>
</section>
JS
$(document).ready(function() {
new Siema({
selector: '.images',
onChange: () => {
console.log("swiped");
// change active indicator?
},
});
});
I think I can help (I'm the author of Siema).
// extend a Siema class and add addDots() & updateDots() methods
const mySiemaWithDots = new SiemaWithDots({
// on init trigger method created above
onInit: function(){
this.addDots();
this.updateDots();
},
// on change trigger method created above
onChange: function(){
this.updateDots()
},
});
https://codepen.io/pawelgrzybek/pen/boQQWy
Have a lovely day 🥑
I'm new to Angular JS and am trying to create a custom directive that creates img tags based on a list of urls and then performs some DOM manipulation afterward. I want to have the images fade in and out over time, like a slideshow. So far, I've got the images added to the DOM, but I can't find anywhere in the compile or link functions that allows me to manipulate the images, as the ng-repeat doesn't appear to have rendered yet. Any ideas?
The directive:
Logger.app.directive("ngSlideshow", function ($compile) {
return {
restrict: "A",
templateUrl: "templates/slideshow.html",
scope: {
pictures: "=ngSlideshow"
},
link: {
post: function(scope, element, attributes) {
var length = $(element).find("img").length; // 0
}
}
};
});
The template:
<div class="spinner">
<img src="{{picture}}" ng-repeat="picture in pictures" alt="" />
</div>
The view:
<div class="pictures" ng-slideshow="log.pictures"></div>
Thanks!
Chris
I have a ng-repeat list that updates every minute. Its a list of cards that contains stuff like title, description, dates and so on.
In those cards there's also a angular-ui-bootstrap popover which i use to display comments on those cards.
When the list updates, the popover will keep some reference which creates a lot of detached dom elements.
Heres some of the code.
The directive i use.
.directive('mypopover', function ($compile, $templateCache) {
var getTemplate = function (contentType) {
var template = '';
switch (contentType) {
case 'user':
template = $templateCache.get("templateId.html");
break;
}
return template;
}
return {
restrict: "A",
link: function ($scope, element, attrs) {
var popOverContent;
popOverContent = getTemplate("user");
popOverContent = $compile("<span>" + popOverContent + "</span>")($scope);
var options = {
content: popOverContent,
placement: "bottom",
html: true,
trigger: "manual",
selector: '.fa-comment',
date: $scope.date,
animation: true
};
$(element).popover(options).on("mouseenter", function () {
var _this = this;
$(this).popover("show");
$('.popover').linkify();
$(".popover").on("mouseleave", function () {
$(this).popover('destroy');
$('.popover').remove();
});
}).on("mouseleave", function () {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
$(this).popover('destroy');
$('.popover').remove();
}
}, 350);
});
var destroy = function () {
$(element).popover('destroy');
}
$scope.$on("$destroy", function () {
destroy();
});
}
}
})
from the html..
The bo-something is the just a one way bind i use instead of the normal double bind from angular
<a bo-href="c.ShortUrl" target="_blank" bindonce ng-repeat="c in cards | filter:searchText | limitTo: limitValue[$index] track by c.Id">
<div class="panel detachable-card">
<div class="panel-body" bo-class="{redLabel: c.RedLabel, orangeLabel: c.OrangeLabel}">
<!-- Comments if any -->
<script type="text/ng-template" id="templateId.html">
<div ng-repeat="comment in c.Comment track by $index">
<strong style="margin-bottom: 20px; color:#bbbbbb; white-space: pre-wrap;">{{c.CommentMember[$index]}}</strong>
<br />
<span style="white-space: pre-wrap;">{{comment}}</span>
<hr />
</div>
</script>
<span bo-if="c.Comment" data-container="body" mypopover style="float:right"><i class="fa fa-comment fa-lg"></i></span>
<!-- Card info -->
<strong style="font-size:12px; color:#999999"><span bo-if="!c.BoardNameOverride" bo-text="c.NameBoard"></span> <span bo-if="c.BoardNameOverride" bo-text="c.BoardNameOverride"></span></strong>
<br />
<strong bo-text="c.Name"></strong>
<br />
<span bo-if="c.Desc" bo-text="c.Desc"><br /></span>
</div>
</div>
</a>
Heres a heap-snapshot of the site after one update.
http://i.stack.imgur.com/V4U1O.png
So Im fairly bad at javascript in general, and i have my doubts about the directive. I would have thought that the .popover('destroy') would remove the reference, but it doesnt seem to..
Any help is greatly appreciated..
Why are you constantly destroying the popup over and over? There is no need to destroy the popup every time the mouse is moved. Just show and hide the popup. It's much nicer on memory than constantly destroying and recreating the popup.
But, what you may not realize is that bootstrap components don't play well with AngularJS. Bootstrap components weren't architected in ways that allow the content within them to be updated easily which poses problems when you use them with AngularJS because the update model is built into the framework. And that's why the AngularUI project rewrote their Javascript components from the ground up in AngularJS so they behave as you would expect. I think you'll find those much easier to use.
http://angular-ui.github.io/bootstrap/
If you are using bootstrap 2.3 AngularUI v0.8 was the last version supporting bootstrap v2.3.
I've been using an implementation of this Drag and Drop with AngularJS and jQuery UI:
http://www.smartjava.org/examples/dnd/double.html
With AngularJS 1.0.8 it works flawlessly. With 1.2.11, it doesn't.
When using AngularJS 1.2 and dragging an item from the left list to the right one the model for the destination list updates correctly. However the DOM doesn't update correctly. Here is the directive that's being used from the example:
app.directive('dndBetweenList', function($parse) {
return function(scope, element, attrs) {
// contains the args for this component
var args = attrs.dndBetweenList.split(',');
// contains the args for the target
var targetArgs = $('#'+args[1]).attr('dnd-between-list').split(',');
// variables used for dnd
var toUpdate;
var target;
var startIndex = -1;
// watch the model, so we always know what element
// is at a specific position
scope.$watch(args[0], function(value) {
toUpdate = value;
},true);
// also watch for changes in the target list
scope.$watch(targetArgs[0], function(value) {
target = value;
},true);
// use jquery to make the element sortable (dnd). This is called
// when the element is rendered
$(element[0]).sortable({
items:'li',
start:function (event, ui) {
// on start we define where the item is dragged from
startIndex = ($(ui.item).index());
},
stop:function (event, ui) {
var newParent = ui.item[0].parentNode.id;
// on stop we determine the new index of the
// item and store it there
var newIndex = ($(ui.item).index());
var toMove = toUpdate[startIndex];
// we need to remove him from the configured model
toUpdate.splice(startIndex,1);
if (newParent == args[1]) {
// and add it to the linked list
target.splice(newIndex,0,toMove);
} else {
toUpdate.splice(newIndex,0,toMove);
}
// we move items in the array, if we want
// to trigger an update in angular use $apply()
// since we're outside angulars lifecycle
scope.$apply(targetArgs[0]);
scope.$apply(args[0]);
},
connectWith:'#'+args[1]
})
}
});
Does something need to be updated for this to work properly with Angular 1.2? I feel like it has something to do with the scope.$apply but am not sure.
I see this is an older question, but I recently ran into the exact same issue with the Drag and Drop example. I don’t know what has changed between angular 1.0.8 and 1.2, but it appears to be the digest cycle that causes problems with the DOM. scope.$apply will trigger a digest cycle, but scope.$apply in and of itself is not the issue. Anything that causes a cycle can cause the DOM t get out of sync with the model.
I was able to find a solution to the the problem using the ui.sortable directive. The specific branch that I used is here: https://github.com/angular-ui/ui-sortable/tree/angular1.2. I have not tested with other branches.
You can view a working example here:
http://plnkr.co/edit/atoDX2TqZT654dEicqeS?p=preview
Using the ui-sortable solution, the ‘dndBetweenList’ directive gets replaced with the ui-sortable directive. Then there are a few changes to make.
In the HTML
<div class="row">
<div class="span4 offset2">
<ul ui-sortable="sortableOptions" ng-model="source" id="sourceList" ng-class="{'minimalList':sourceEmpty()}" class="connector">
<li class="alert alert-danger nomargin" ng-repeat="item in source">{{item.value}}</li>
</ul>
</div>
<div class="span4">
<ul ui-sortable="sortableOptions" id="targetList" ng-model="model" ng-class="{'minimalList':sourceEmpty()}" class="connector">
<li class="alert alert-info nomargin" ng-repeat="item in model">{{item.value}}</li>
</ul>
</div>
</div>
Note the dnd-between-list directive is no longer needed and is replaced with the ui-sortable.
In the module inject the ui-sortable, and in the controller specify that sortable options. The sortable accepts the same options as the jquery sortable.
app.js
var app = angular.module('dnd', ['ui.sortable']);
ctrl-dnd.js
$scope.sortableOptions = {
connectWith: '.connector'
}
Only the additions to the controller are shown. Note that I added a .connector class on the ul. In the sortable I use .connector for the connectWith option.
I'm trying to create a menu bar using Angularjs. I've done similar things before with Backbonejs, but I have a hard time getting my head around how to do this with angular.
In my html file, I have the following menu placeholder.
<div id='menu1'></div>
<div id='menu2'></div>
<div id='menu3'></div>
<div id='menu4'></div>
<div id='menu5'></div>
A number of my angular modules add a menu when they are loaded (in run). Each of them only reserves a particular slot (i.e. menu1..5), so they don't clash. When some modules aren't loaded, their menu would not show in the menu bar.
An angular module would conceptually look like:
angular.module('myModule3', [])
.service('someService', function($http) {
// get some data to populate menu (use $http)
this.menuItems = ['orange', 'apple', 'banana']
})
.run(['someService', function(someService) {
// create a rendered menu item
...
// insert it at id="menu3"
})
For sake of simplicity, the rendered menu item should look like:
<ul>
<li>organge</li>
<li>apple</li>
<li>banana</li>
</ul>
I'm fairly new to angular, so I don't really know where to begin. I've been reading up on directives, but don't see how they fit in here, as they require some custom markup (maybe a custom menu tag containing the DOM target (i.e. menu..5). Also, how to connect this to a controller is not clear to me.
Update
In addition to the above base template (containing arbitrary anchor points in the DOM) and the directive (which will produce a DOM element which will be inserted at these anchor points), a template will facilitate the creation of the DOM element. This template will be located in a separate file containing the position the directive's DOM element will be inserted to (as opposed to the usual case of directives in which an already existing tag will be replaced/inserted into specific markup that matches the directive's definition:
<menu ng-model="Model3DataService" target="#menu3">
<ul>
<li ng-repeat="for item in items"></li>
</ul>
</menu>
Again, coming from a Backbone/jquery background this makes sense, but this may not be the right thing to do in angular. If so, please let me know how I could keep the base template free of any knowledge about the modules and assumptions of where they put their menu (i.e. which slot of the menu bar they allocate). I'm happy to hear about other solutions...
Each module should have its menu loader defined:
angular.module('module1', []).
factory('module1.menuLoader', function() {
return function(callback) {
callback(['oranges', 'bananas'])
}
});
Your application should contain menu directive which can load menu items for any module only if exists.
angular.module('app', ['module1']).
directive('menu', ['$injector', function($injector) {
return {
restrict: 'A',
template:
'<ul><li ng-repeat="item in items">{{item}}</li></ul>',
scope: {},
link: function($scope, $element, $attrs) {
var menuLoaderName = $attrs.menu+'.menuLoader';
if ($injector.has(menuLoaderName)) {
var loaderFn = $injector.get(menuLoaderName);
loaderFn(function(menuItems) {
$scope.items = menuItems;
});
}
}
};
}]);
Final html:
<div class="content">
<div menu="module1"></div>
<div menu="module2"></div>
<div menu="module3"></div>
</div>
After running the application only module1 menu will be loaded. Other menu placeholders remain empty.
Live demo: http://plnkr.co/edit/4tZQGSkJToGCirQ1cmb6
Updated: If you want to generate markup on the module side the best way is to put the template to the $templateCache in the module where it's defined and then pass the templateName to the application.
angular.module('module1', []).
factory('module1.menuLoader', ['$templateCache', function($templateCache) {
$templateCache.put('module1Menu', '<ul><li ng-repeat="item in items">{{item}}</li></ul>');
return function(callback) {
callback('module1Menu', ['oranges', 'bananas'])
}
}]);
angular.module('app', ['module1'])
.directive('menu', ['$injector', function($injector) {
return {
restrict: 'A',
template:
'<div ng-include="menuTemplate"></div>',
scope: {},
link: function($scope, $element, $attrs) {
var menuLoaderName = $attrs.menu+'.menuLoader';
if ($injector.has(menuLoaderName)) {
var loaderFn = $injector.get(menuLoaderName);
loaderFn(function(menuTemplate, menuItems) {
$scope.menuTemplate = menuTemplate;
$scope.items = menuItems;
});
}
}
};
}]);