Im creating a hybrid application using Cordova, AngularJs and Ionic. Im getting my data from Wordpress using a JSON API plugin.
Here is my single post view :
<ion-view view-title="Single View">
<ion-content>
<div class="card single-view" ng-show="show_post">
<div class="title" ng-bind-html="data['post'].title"></div>
<div class="thumb">
<img ng-src="{{data['post'].thumbnail_images['single-post-thumb'].url}}" />
</div>
<div class="content" ng-bind-html="data['post'].content"></div>
</div>
</ion-content>
</ion-view>
Is there any way to add a click listener on every image that will be generated on my content div, so i can open a modal with a full size image when i click on it thumb ?
P.S: I dont use jquery, In JQuery it will be something like :
$('.content > a > img ').bind("click", function(e){
//open my modal..
});
Simply create a directive with a link function that will add the plugin and decorate all your images with it. Something like this:
<img ng-src="{{url}}" image-modal />
and
app.directive('imageModal', function() {
return {
link: function(scope, elem, attrs) {
var options = {}; // settings.
elem.modal(options);
// maybe add a elem.on('click', function(){}) for showing the modal
}
};
});
I finally managed to find a solution !
The data that i recieve from my Wordpress Api contains images inside links, its something like this :
<img src=".." />
So instead of directly putting my html content inside the ng-bind-html, i managed to do something like this :
I save my html content inside a variable then i use the replace function to replace all the href attributes with the ng-click="showImage()" img-src=
$scope.data = items;
var post_content =items['post'].content;
$scope.content=$sce.trustAsHtml(post_content.replace(/href=/gm, 'ng-click="showImage()" img-src='));
I binded this html code using template attribute :
<div class="post-content" template="{{content}}"></div>
I recompiled my html code using a directive like this :
angular.module('starter.controllers', [])
.controller(............)
.directive( 'showData', function ( $compile ) {
return {
scope: true,
link: function ( scope, element, attrs ) {
var el;
attrs.$observe( 'template', function ( tpl ) {
if ( angular.isDefined( tpl ) ) {
el = $compile( tpl )( scope );
element.html("");
element.append( el );
}
});
}
};
});
I just need to know how to check if the href contain an image or not.
The issue is when I try to conditionally apply a 'has-dropdown' attribute, I get the following Angular transclusion error:
Error: [$compile:ctreq] Controller 'hasDropdown', required by directive 'ngTransclude', can't be found!
It references angular.js line 9563
. The logic I am trying to apply is:
If the subNav array is empty, then do not display the 'has-dropdown' attribute in the element.
If it is not empty, then add the 'has-dropdown' attribute.
Anything that I'm missing?
<code>
<li ng-repeat="nav in app.mainNavItems"
{{app.mainNavItems.subNavs.length > 0 ? "has-dropdown" : ""}}>
</code>
You can't do this in this way. You should create a directive, which on compile stage should check if app.mainNavItems.subNavs.length > 0 and add attribute with $element.attr('has-dropdown')
Something like this:
var myModule = angular.module(...);
myModule.directive('directiveName', function($parse) {
return {
restrict: 'A',
compile: function compile(tElement, tAttrs, transclude) {
if($parse(tAttrs.directiveName)()) {
tElement.attr('has-dropdown');
}
}
};
});
template:
<li ng-repeat="nav in app.mainNavItems" directive-name="app.mainNavItems.subNavs.length > 0">
Note: not tested, just from the top of my head..
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 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
I want to call some jQuery function targeting div with table. That table is populated with ng-repeat.
When I call it on
$(document).ready()
I have no result.
Also
$scope.$on('$viewContentLoaded', myFunc);
doesn't help.
Is there any way to execute function right after ng-repeat population completes? I've read an advice about using custom directive, but I have no clue how to use it with ng-repeat and my div...
Indeed, you should use directives, and there is no event tied to the end of a ng-Repeat loop (as each element is constructed individually, and has it's own event). But a) using directives might be all you need and b) there are a few ng-Repeat specific properties you can use to make your "on ngRepeat finished" event.
Specifically, if all you want is to style/add events to the whole of the table, you can do so using in a directive that encompasses all the ngRepeat elements. On the other hand, if you want to address each element specifically, you can use a directive within the ngRepeat, and it will act on each element, after it is created.
Then, there are the $index, $first, $middle and $last properties you can use to trigger events. So for this HTML:
<div ng-controller="Ctrl" my-main-directive>
<div ng-repeat="thing in things" my-repeat-directive>
thing {{thing}}
</div>
</div>
You can use directives like so:
angular.module('myApp', [])
.directive('myRepeatDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('color','blue');
if (scope.$last){
window.alert("im the last!");
}
};
})
.directive('myMainDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('border','5px solid red');
};
});
See it in action in this Plunker.
If you simply want to execute some code at the end of the loop, here's a slightly simpler variation that doesn't require extra event handling:
<div ng-controller="Ctrl">
<div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
thing {{thing}}
</div>
</div>
function Ctrl($scope) {
$scope.things = [
'A', 'B', 'C'
];
}
angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
return function(scope, element, attrs) {
if (scope.$last){
// iteration is complete, do whatever post-processing
// is necessary
element.parent().css('border', '1px solid black');
}
};
});
See a live demo.
There is no need of creating a directive especially just to have a ng-repeat complete event.
ng-init does the magic for you.
<div ng-repeat="thing in things" ng-init="$last && finished()">
the $last makes sure, that finished only gets fired, when the last element has been rendered to the DOM.
Do not forget to create $scope.finished event.
Happy Coding!!
EDIT: 23 Oct 2016
In case you also want to call the finished function when there is no item in the array then you may use the following workaround
<div style="display:none" ng-init="things.length < 1 && finished()"></div>
//or
<div ng-if="things.length > 0" ng-init="finished()"></div>
Just add the above line on the top of the ng-repeat element. It will check if the array is not having any value and call the function accordingly.
E.g.
<div ng-if="things.length > 0" ng-init="finished()"></div>
<div ng-repeat="thing in things" ng-init="$last && finished()">
Here is a repeat-done directive that calls a specified function when true. I have found that the called function must use $timeout with interval=0 before doing DOM manipulation, such as initializing tooltips on the rendered elements. jsFiddle: http://jsfiddle.net/tQw6w/
In $scope.layoutDone, try commenting out the $timeout line and uncommenting the "NOT CORRECT!" line to see the difference in the tooltips.
<ul>
<li ng-repeat="feed in feedList" repeat-done="layoutDone()" ng-cloak>
{{feed | strip_http}}
</li>
</ul>
JS:
angular.module('Repeat_Demo', [])
.directive('repeatDone', function() {
return function(scope, element, attrs) {
if (scope.$last) { // all are rendered
scope.$eval(attrs.repeatDone);
}
}
})
.filter('strip_http', function() {
return function(str) {
var http = "http://";
return (str.indexOf(http) == 0) ? str.substr(http.length) : str;
}
})
.filter('hostName', function() {
return function(str) {
var urlParser = document.createElement('a');
urlParser.href = str;
return urlParser.hostname;
}
})
.controller('AppCtrl', function($scope, $timeout) {
$scope.feedList = [
'http://feeds.feedburner.com/TEDTalks_video',
'http://feeds.nationalgeographic.com/ng/photography/photo-of-the-day/',
'http://sfbay.craigslist.org/eng/index.rss',
'http://www.slate.com/blogs/trending.fulltext.all.10.rss',
'http://feeds.current.com/homepage/en_US.rss',
'http://feeds.current.com/items/popular.rss',
'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml'
];
$scope.layoutDone = function() {
//$('a[data-toggle="tooltip"]').tooltip(); // NOT CORRECT!
$timeout(function() { $('a[data-toggle="tooltip"]').tooltip(); }, 0); // wait...
}
})
Here's a simple approach using ng-init that doesn't even require a custom directive. It's worked well for me in certain scenarios e.g. needing to auto-scroll a div of ng-repeated items to a particular item on page load, so the scrolling function needs to wait until the ng-repeat has finished rendering to the DOM before it can fire.
<div ng-controller="MyCtrl">
<div ng-repeat="thing in things">
thing: {{ thing }}
</div>
<div ng-init="fireEvent()"></div>
</div>
myModule.controller('MyCtrl', function($scope, $timeout){
$scope.things = ['A', 'B', 'C'];
$scope.fireEvent = function(){
// This will only run after the ng-repeat has rendered its things to the DOM
$timeout(function(){
$scope.$broadcast('thingsRendered');
}, 0);
};
});
Note that this is only useful for functions you need to call one time after the ng-repeat renders initially. If you need to call a function whenever the ng-repeat contents are updated then you'll have to use one of the other answers on this thread with a custom directive.
Complementing Pavel's answer, something more readable and easily understandable would be:
<ul>
<li ng-repeat="item in items"
ng-init="$last ? doSomething() : angular.noop()">{{item}}</li>
</ul>
Why else do you think angular.noop is there in the first place...?
Advantages:
You don't have to write a directive for this...
Maybe a bit simpler approach with ngInit and Lodash's debounce method without the need of custom directive:
Controller:
$scope.items = [1, 2, 3, 4];
$scope.refresh = _.debounce(function() {
// Debounce has timeout and prevents multiple calls, so this will be called
// once the iteration finishes
console.log('we are done');
}, 0);
Template:
<ul>
<li ng-repeat="item in items" ng-init="refresh()">{{item}}</li>
</ul>
Update
There is even simpler pure AngularJS solution using ternary operator:
Template:
<ul>
<li ng-repeat="item in items" ng-init="$last ? doSomething() : null">{{item}}</li>
</ul>
Be aware that ngInit uses pre-link compilation phase - i.e. the expression is invoked before child directives are processed. This means that still an asynchronous processing might be required.
It may also be necessary when you check the scope.$last variable to wrap your trigger with a setTimeout(someFn, 0). A setTimeout 0 is an accepted technique in javascript and it was imperative for my directive to run correctly.
I did it this way.
Create the directive
function finRepeat() {
return function(scope, element, attrs) {
if (scope.$last){
// Here is where already executes the jquery
$(document).ready(function(){
$('.materialboxed').materialbox();
$('.tooltipped').tooltip({delay: 50});
});
}
}
}
angular
.module("app")
.directive("finRepeat", finRepeat);
After you add it on the label where this ng-repeat
<ul>
<li ng-repeat="(key, value) in data" fin-repeat> {{ value }} </li>
</ul>
And ready with that will be run at the end of the ng-repeat.
<div ng-repeat="i in items">
<label>{{i.Name}}</label>
<div ng-if="$last" ng-init="ngRepeatFinished()"></div>
</div>
My solution was to add a div to call a function if the item was the last in a repeat.
This is an improvement of the ideas expressed in other answers in order to show how to gain access to the ngRepeat properties ($index, $first, $middle, $last, $even, $odd) when using declarative syntax and isolate scope (Google recommended best practice) with an element-directive. Note the primary difference: scope.$parent.$last.
angular.module('myApp', [])
.directive('myRepeatDirective', function() {
return {
restrict: 'E',
scope: {
someAttr: '='
},
link: function(scope, element, attrs) {
angular.element(element).css('color','blue');
if (scope.$parent.$last){
window.alert("im the last!");
}
}
};
});
i would like to add another answer, since the preceding answers takes it that the code needed to run after the ngRepeat is done is an angular code, which in that case all answers above give a great and simple solution, some more generic than others, and in case its important the digest life cycle stage you can take a look at Ben Nadel's blog about it, with the exception of using $parse instead of $eval.
but in my experience, as the OP states, its usually running some JQuery plugins or methods on the finnaly compiled DOM, which in that case i found that the most simple solution is to create a directive with a setTimeout, since the setTimeout function gets pushed to the end of the queue of the browser, its always right after everything is done in angular, usually ngReapet which continues after its parents postLinking function
angular.module('myApp', [])
.directive('pluginNameOrWhatever', function() {
return function(scope, element, attrs) {
setTimeout(function doWork(){
//jquery code and plugins
}, 0);
};
});
for whoever wondering that in that case why not to use $timeout, its that it causes another digest cycle that is completely unnecessary
I had to render formulas using MathJax after ng-repeat ends, none of the above answers solved my problem, so I made like below. It's not a nice solution, but worked for me...
<div ng-repeat="formula in controller.formulas">
<div>{{formula.string}}</div>
{{$last ? controller.render_formulas() : ""}}
</div>
I found an answer here well practiced, but it was still necessary to add a delay
Create the following directive:
angular.module('MyApp').directive('emitLastRepeaterElement', function() {
return function(scope) {
if (scope.$last){
scope.$emit('LastRepeaterElement');
}
}; });
Add it to your repeater as an attribute, like this:
<div ng-repeat="item in items" emit-last-repeater-element></div>
According to Radu,:
$scope.eventoSelecionado.internamento_evolucoes.forEach(ie => {mycode});
For me it works, but I still need to add a setTimeout
$scope.eventoSelecionado.internamento_evolucoes.forEach(ie => {
setTimeout(function() {
mycode
}, 100); });
If you simply wants to change the class name so it will rendered differently, below code would do the trick.
<div>
<div ng-show="loginsuccess" ng-repeat="i in itemList">
<div id="{{i.status}}" class="{{i.status}}">
<div class="listitems">{{i.item}}</div>
<div class="listitems">{{i.qty}}</div>
<div class="listitems">{{i.date}}</div>
<div class="listbutton">
<button ng-click="UpdateStatus(i.$id)" class="btn"><span>Done</span></button>
<button ng-click="changeClass()" class="btn"><span>Remove</span></button>
</div>
<hr>
</div>
This code worked for me when I had a similar requirement to render the shopped item in my shopping list in Strick trough font.