Angular - directive to repeat images - javascript

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

Related

Small Images not Zooming using ElevateZoom plugin

I am using ElevateZoom plugin in my application. If the image resolution is good it is able to zoom but when the image resolution is small it's not working.
Here is the code:
description.jsp
<img ng-if="mlist.typeId===1"
ng-elevate-zoom
zoom-image="{{mlist.mediaUrl}}" id="zimg{{$index}}"
actual-src="{{mlist.mediaUrl}}" loader-src="resources/images/loading.gif" loader-class="preloader" showloader
class="img-responsive zoomImg" alt=""/>
where zoom-image, actual-src data-zoom-image all having same image.
app.js
app.directive('ngElevateZoom', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
//Will watch for changes on the attribute
attrs.$observe('zoomImage',function(){
linkElevateZoom();
})
function linkElevateZoom(){
//Check if its not empty
if (!attrs.zoomImage) return;
element.attr('data-zoom-image',attrs.zoomImage);
$(element).elevateZoom({zoomType:"lens", cursor:"crosshair"/*, lensSize:250*//**/ /*scrollZoom:true*//*, containLensZoom:true*/});
}
linkElevateZoom();
}
};
});
Plugin : elevatezoom

AngularJS parallax effect directive not applying on application load

I'm creating application using AngularJS + ngRoute module + Angular Bootstrap UI. I've created index.html page and few templates, that are being loaded through ng-view directive placed in index.html.
Currently I'm trying to make parallax effect on background images, based on this plugin:
https://github.com/brettdonohoo/angular-parallax
http://brettdonohoo.com/angular-parallax/index.html
In one of my views I have DIV element, that has parallax directive on it.
<div parallax-background parallax-offset="0.4" parallax-ratio="0.7" class="slide" style="background-image: url('{{covers[0].image}}')" ng-click="open(covers[0])"></div>
The problem is - when I'm loading application, the directive is fired correctly on the DIV element, but the background-position css does not change. When I scroll window - background-position changes OK. But I need the position to be applied on initial change too.
When I move my DIV element out of the template to the index.html it works. But of course I would like it to display only one one subpage.
My directive:
.directive('parallaxBackground', ['$window',
function ($window) {
return {
restrict: 'A',
transclude: true,
template: '<div ng-transclude></div>',
scope: {
parallaxRatio: '#',
parallaxOffset: '#',
},
link: function ($scope, elem, attrs) {
var setPosition = function () {
var calcValY = (elem.prop('offsetTop') - $window.pageYOffset) * ($scope.parallaxRatio ? $scope.parallaxRatio : 1.1) - ($scope.parallaxOffset ? $scope.parallaxOffset : 0) * $window.innerHeight;
elem.css('background-position', "50% " + calcValY + "px");
};
angular.element($window).bind('load', function (e) {
setPosition();
$scope.$apply();
});
angular.element($window).bind("scroll", setPosition);
} // link function
};
}
]);

AngularJS ng-switch without extra DOM

I have a custom directive and an object myObj on the current $scope (inside an ng-repeat).
If the object has a type of html, I want to use one template:
<span ng-bind-html="myObj.html"></span>`
Otherwise I want to use a different template:
<span>{{myObj.value}}</span>`
My problem
This is invalid because a custom directive template must contain exactly one root node:
<span ng-if="myObj.type==='html'" ng-bind-html="myObj.html"></span>
<span ng-if="myObj.type!=='html'">{{myObj.value}}</span>
This is invalid because it destroys my page with extra DOM: (wrapping all my spans (there could be thousands) in unnecessary ng-switch nodes...)
<ng-switch on="myObj.type">
<span ng-switch-when="html" ng-bind-html="myObj.html"></span>
<span ng-switch-default>{{myObj.value}}</span>
</ng-switch>
My Question
Is it possible to have a directive pick it's template based on the result of a switch, without creating extra unnecessary DOM? For example, you can specify replace: true when creating a directive - is it possible to similarly have an ng-switch where the result replaces the switch tag itself?
Edit
My Directive:
return {
replace: true,
controller: 'ChunkController',
scope: {
chunk: '=deChunk'
},
templateUrl: de.partial.chunk,
link: function (scope, el, attr, ctrl) {
el.on('keydown', handleKeypress.bind(ctrl));
el.on('click', ctrl.showValue);
}
};
And its usage:
<div class="content" contenteditable="{{node.type!=='static'}}">
<div data-ng-repeat="chunk in node.chunks" data-de-chunk="chunk"></div>
</div>
With the intent that the child <div> will be replaced with the sequence of <span>s from above.
I wouldn't even bother if you are storing the html in a service just check to see if a value for myObj.html exists in the object and if it does compile and bind the html in the linker function instead of using ng-bind-html
something like this maybe:
myapp.directive('something',function($compile){
return {
link: function(scope,elem,attrs) {
var obj = scope.$eval(attrs.something);
if(obj.html) {
var html = angular.element($compile(obj.html)(scope));
elem.append(html);
} else {
//go get the data and set obj.html
}
}
}
});

AngularJS: Truncate multi-line HTML bound in ng-repeat/ng-bind-html

I have following ng-repeat
<div class="item-post" ng-repeat="item in items">
<div class="item-content" ng-bind-html="item.text"></div>
</div>
where item.text is multi-line HTML text and it displays correctly, but I need to truncate it to max-height of item-post div (250px). And then append three dots signalizing that text is longer.
I wanted to use jquery.autoellipsis which is working for example on div with static content.
For AngularJS I have found angular-ellipsis, but is doesn't work with HTML, only plain text. I need to achieve it on HTML content.
Thanks in advance for help!
EDIT/SOLUTION:
Finally I have been able to use jquery.autoellipsis plugin using custom directive (based on asgoth's answer):
myDirectives.directive('htmlEllipsis', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$timeout(function() {
angular.element(element).ellipsis();
}, 0);
}
};
}]);
And in partial view:
<div class="item-post" ng-repeat="item in items">
<div class="item-content" ng-bind-html="item.text" html-ellipsis></div>
</div>
EDIT2:
Directive from asgoth's answer after his edit works well, using another approach than above-mentioned directive.
If I were you I would make a directive to use the jquery plugin (jquery.autoellipsis):
angular.module('myModule').directive('ellipsis', [function () {
return {
required: 'ngBindHtml',
restrict: 'A',
priority: 100,
link: function ($scope, element, attrs, ctrl) {
$scope.hasEllipsis = false;
$scope.$watch(element.html(), function(value) {
if (!$scope.hasEllipsis) {
// apply ellipsis only one
$scope.hasEllipsis = true;
element.ellipsis();
}
});
}
};
}]);
Your html is then:
<div class="item-content" ng-bind-html="item.text" ellipsis></div>
Of course, you need to include the jquery plugin in a script tag.
EDIT: I've edited the answer, so the directive will watch for the html to change (done by ngBindHtml).
Similar to the accepted answer, this alternative allows improved customization: https://github.com/dibari/angular-ellipsis

Dynamic menu bar with angularjs

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

Categories