How to get async html attribut - angularjs

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

Related

Image loading issue in custom directive

I want the image URL received from server side in my custom directive.
The directive is used to create a canvas.
Seems the directive is loaded and the image URL is undefined. As it takes the time to get the URL from the server side.
Or maybe how did I get $rootScope data in my directive link function.
Edit:
The following is the directive:
app.directive('logocanvasdirective',['$rootScope','$templateRequest','$compile', function($rootScope,$templateRequest,$compile) {
return {
template: "<canvas id='logo' width='500' height='500'/>",
scope: true,
link: function($scope, element, attrs) {
var canvas1 = document.getElementById('logo'),
context1 = canvas1.getContext('2d');
make_base1();
function make_base1()
{
base_image1 = new Image();
base_image1.src =scope.variable; //How do I use this?
base_image1.onload = function() {
context1.drawImage(base_image1, 0, 0);
}
}
}
};
}]);
I want the image.src = $scope.variable which is receive from server side in my controller.
How do I do that ?
You need to use $watch since you are getting the src from an asynchronous AJAX call:
app.directive('logocanvasdirective',['$rootScope','$templateRequest','$compile', function($rootScope,$templateRequest,$compile) {
return {
template: "<canvas id='logo' width='500' height='500'/>",
scope: {
imgSrc: '='
},
link: function($scope, element, attrs) {
var canvas1 = document.getElementById('logo'),
context1 = canvas1.getContext('2d');
make_base1();
function make_base1()
{
base_image1 = new Image();
base_image1.src = scope.imgSrc;
base_image1.onload = function() {
context1.drawImage(base_image1, 0, 0);
}
}
scope.$watch('imgSrc', function(newValue) {
if (newValue) {
make_base1();
}
});
}
};
}]);
And pass the $scope.variable to your directive:
<logocanvasdirective img-src="variable" />
Or
<div logocanvasdirective img-src="variable"></div>

How to detect all imges loading finished in AngularJS

I want to use ng-repeat to show more then 100 images in a page. Those images are taking significant time in loading and i don't want to show them getting loaded to the users. So, I only want show them after all of them are loaded in the browser.
Is there a way to detect, if all the images are loaded?
you can use load event like this.
image.addEventListener('load', function() {
/* do stuff */
});
Angular Directives
Solution for single image
HTML
<div ng-app="myapp">
<div ng-controller="MyCtrl1">
<loaded-img src="src"></loaded-img>
<img ng-src="{{src2}}" />'
</div>
</div>
JS
var myApp = angular.module('myapp',[]);
myApp
.controller('MyCtrl1', function ($scope) {
$scope.src = "http://lorempixel.com/800/200/sports/1/";
$scope.src2 = "http://lorempixel.com/800/200/sports/2/";
})
.directive('loadedImg', function(){
return {
restrict: 'E',
scope: {
src: '='
},
replace: true,
template: '<img ng-src="{{src}}" class="none"/>',
link: function(scope, ele, attr){
ele.on('load', function(){
ele.removeClass('none');
});
}
};
});
CSS
.none{
display: none;
}
http://jsfiddle.net/jigardafda/rqkor67a/4/
if you see the jsfiddle demo, you will notice src image is only showing after image is fully loaded whereas in case of src2 you can see image loading.(disable cache to see the difference)
Solution for multiple images
HTML
<div ng-app="myapp">
<div ng-controller="MyCtrl1">
<div ng-repeat="imgx in imgpaths" ng-hide="hideall">
<loaded-img isrc="imgx.path" onloadimg="imgx.callback(imgx)"></loaded-img>
</div>
</div>
</div>
JS
var myApp = angular.module('myapp',[]);
myApp
.controller('MyCtrl1', function ($scope, $q) {
var imp = 'http://lorempixel.com/800/300/sports/';
var deferred;
var dArr = [];
var imgpaths = [];
for(var i = 0; i < 10; i++){
deferred = $q.defer();
imgpaths.push({
path: imp + i,
callback: deferred.resolve
});
dArr.push(deferred.promise);
}
$scope.imgpaths = imgpaths;
$scope.hideall = true;
$q.all(dArr).then(function(){
$scope.hideall = false;
console.log('all loaded')
});
})
.directive('loadedImg', function(){
return {
restrict: 'E',
scope: {
isrc: '=',
onloadimg: '&'
},
replace: true,
template: '<img ng-src="{{isrc}}" class="none"/>',
link: function(scope, ele, attr){
ele.on('load', function(){
console.log(scope.isrc, 'loaded');
ele.removeClass('none');
scope.onloadimg();
});
}
};
});
To detect if all images are loaded,
for each image i generated a deferred object and passed its deferred.resolve as a image onload callback of the directive and then pushed that deferred objects promise in an array. and after that i used $q.all to detect if all those promise are yet resolved or not.
http://jsfiddle.net/jigardafda/rqkor67a/5/
UPDATE: angular way added.
UPDATE: added solution for loading multiple images.
Check if all images are loaded
jQuery.fn.extend({
imagesLoaded: function( callback ) {
var i, c = true, t = this, l = t.length;
for ( i = 0; i < l; i++ ) {
if (this[i].tagName === "IMG") {
c = (c && this[i].complete && this[i].height !== 0);
}
}
if (c) {
if (typeof callback === "function") { callback(); }
} else {
setTimeout(function(){
jQuery(t).imagesLoaded( callback );
}, 200);
}
}
});
Callback occurs when all images are loaded
image load errors are ignored (complete will be true)
Use:
$('.wrap img').imagesLoaded(function(){
alert('all images loaded');
});
Note : this code worked for me, Source :
http://wowmotty.blogspot.in/2011/12/all-images-loaded-imagesloaded.html

Load Angular Directive Template Async

I want to be able to load the directive's template from a promise. e.g.
template: templateRepo.get('myTemplate')
templateRepo.get returns a promise, that when resolved has the content of the template in a string.
Any ideas?
You could load your html inside your directive apply it to your element and compile.
.directive('myDirective', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
//Some arbitrary promise.
fetchHtml()
.then(function(result){
element.html(result);
$compile(element.contents())(scope);
}, function(error){
});
}
}
});
This is really interesting question with several answers of different complexity. As others have already suggested, you can put loading image inside directive and when template is loaded it'll be replaced.
Seeing as you want more generic loading indicator solution that should be suitable for other things, I propose to:
Create generic service to control indicator with.
Manually load template inside link function, show indicator on request send and hide on response.
Here's very simplified example you can start with:
<button ng-click="more()">more</button>
<div test="item" ng-repeat="item in items"></div>
.throbber {
position: absolute;
top: calc(50% - 16px);
left: calc(50% - 16px);
}
angular
.module("app", [])
.run(function ($rootScope) {
$rootScope.items = ["One", "Two"];
$rootScope.more = function () {
$rootScope.items.push(Math.random());
};
})
.factory("throbber", function () {
var visible = false;
var throbber = document.createElement("img");
throbber.src = "http://upload.wikimedia.org/wikipedia/en/2/29/Throbber-Loadinfo-292929-ffffff.gif";
throbber.classList.add("throbber");
function show () {
document.body.appendChild(throbber);
}
function hide () {
document.body.removeChild(throbber);
}
return {
show: show,
hide: hide
};
})
.directive("test", function ($templateCache, $timeout, $compile, $q, throbber) {
var template = "<div>{{text}}</div>";
var templateUrl = "templateUrl";
return {
link: function (scope, el, attr) {
var tmpl = $templateCache.get(templateUrl);
if (!tmpl) {
throbber.show();
tmpl = $timeout(function () {
return template;
}, 1000);
}
$q.when(tmpl).then(function (value) {
$templateCache.put(templateUrl, value);
el.html(value);
$compile(el.contents())(scope);
throbber.hide();
});
},
scope: {
text: "=test"
}
};
});
JSBin example.
In live code you'll have to replace $timeout with $http.get(templateUrl), I've used the former to illustrate async loading.
How template loading works in my example:
Check if there's our template in $templateCache.
If no, fetch it from URL and show indicator.
Manually put template inside element and [$compile][2] it.
Hide indicator.
If you wonder what $templateCache is, read the docs. AngularJS uses it with templateUrl by default, so I did the same.
Template loading can probably be moved to decorator, but I lack relevant experience here. This would separate concerns even further, since directives don't need to know about indicator, and get rid of boilerplate code.
I've also added ng-repeat and run stuff to demonstrate that template doesn't trigger indicator if it was already loaded.
What I would do is to add an ng-include in my directive to selectively load what I need
Check this demo from angular page. It may help:
http://docs.angularjs.org/api/ng.directive:ngInclude
````
/**
* async load template
* eg :
* <div class="ui-header">
* {{data.name}}
* <ng-transclude></ng-transclude>
* </div>
*/
Spa.Service.factory("RequireTpl", [
'$q',
'$templateCache',
'DataRequest',
'TplConfig',
function(
$q,
$templateCache,
DataRequest,
TplConfig
) {
function getTemplate(tplName) {
var name = TplConfig[tplName];
var tpl = "";
if(!name) {
return $q.reject(tpl);
} else {
tpl = $templateCache.get(name) || "";
}
if(!!tpl) {
return $q.resolve(tpl);
}
//加载还未获得的模板
return new $q(function(resolve, reject) {
DataRequest.get({
url : "/template/",
action : "components",
responseType : "text",
components : name
}).success(function(tpl) {
$templateCache.put(name, tpl);
resolve(tpl);
}).error(function() {
reject(null);
});
});
}
return getTemplate;
}]);
/**
* usage:
* <component template="table" data="info">
* <span>{{info.name}}{{name}}</span>
* </component>
*/
Spa.Directive.directive("component", [
"$compile",
"RequireTpl",
function(
$compile,
RequireTpl
) {
var directive = {
restrict : 'E',
scope : {
data : '='
},
transclude : true,
link: function ($scope, element, attrs, $controller, $transclude) {
var linkFn = $compile(element.contents());
element.empty();
var tpl = attrs.template || "";
RequireTpl(tpl)
.then(function(rs) {
var tplElem = angular.element(rs);
element.replaceWith(tplElem);
$transclude(function(clone, transcludedScope) {
if(clone.length) {
tplElem.find("ng-transclude").replaceWith(clone);
linkFn($scope);
} else {
transcludedScope.$destroy()
}
$compile(tplElem.contents())($scope);
}, null, "");
})
.catch(function() {
element.remove();
console.log("%c component tpl isn't exist : " + tpl, "color:red")
});
}
};
return directive;
}]);
````

AngularJS Passing Variable to Directive

I'm new to angularjs and am writing my first directive. I've got half the way there but am struggling figuring out how to pass some variables to a directive.
My directive:
app.directive('chart', function () {
return{
restrict: 'E',
link: function (scope, elem, attrs) {
var chart = null;
var opts = {};
alert(scope[attrs.chartoptions]);
var data = scope[attrs.ngModel];
scope.$watch(attrs.ngModel, function (v) {
if (!chart) {
chart = $.plot(elem, v, opts);
elem.show();
} else {
chart.setData(v);
chart.setupGrid();
chart.draw();
}
});
}
};
});
My controller:
function AdListCtrl($scope, $http, $rootScope, $compile, $routeParams, AlertboxAPI) {
//grabing ad stats
$http.get("/ads/stats/").success(function (data) {
$scope.exports = data.ads;
if ($scope.exports > 0) {
$scope.show_export = true;
} else {
$scope.show_export = false;
}
//loop over the data
var chart_data = []
var chart_data_ticks = []
for (var i = 0; i < data.recent_ads.length; i++) {
chart_data.push([0, data.recent_ads[i].ads]);
chart_data_ticks.push(data.recent_ads[i].start);
}
//setup the chart
$scope.data = [{data: chart_data,lines: {show: true, fill: true}}];
$scope.chart_options = {xaxis: {ticks: [chart_data_ticks]}};
});
}
My Html:
<div class='row-fluid' ng-controller="AdListCtrl">
<div class='span12' style='height:400px;'>
<chart ng-model='data' style='width:400px;height:300px;display:none;' chartoptions="chart_options"></chart>
{[{ chart_options }]}
</div>
</div>
I can access the $scope.data in the directive, but I can't seem to access the $scope.chart_options data.. It's definelty being set as If I echo it, it displays on the page..
Any ideas what I'm doing wrong?
UPDATE:
For some reason, with this directive, if I move the alert(scope[attrs.chartoptions]); to inside the $watch, it first alerts as "undefined", then again as the proper value, otherwise it's always undefined. Could it be related to the jquery flot library I'm using to draw the chart?
Cheers,
Ben
One problem I see is here:
scope.$watch(attrs.ngModel, function (v) {
The docs on this method are unfortunately not that clear, but the first argument to $watch, the watchExpression, needs to be an angular expression string or a function. So in your case, I believe that you need to change it to:
scope.$watch("attrs.ngModel", function (v) {
If that doesn't work, just post a jsfiddle or jsbin.com with your example.

Jquery Masonry with AngularJS

in my project i try to implement jquery masonry. but its getting working. i try googling but found some post. but i tried it its not working.
my directive code is
shout.directive("shoutList", function($timeout) {
return {
restrict : 'E',
replace : true,
templateUrl : 'views/shout/shout-list.html',
scope : {
shouts : "="
},
//require : "ShoutController",
controller : function($scope) {
$scope.deleteShout = function() {
console.log('shout deleted');
}
},
link : function(scope, element, attr) {
scope.$watch('shouts', function() {
// console.log("changing......");
// scope.$evalAsync(
document.getElementById("shout-content-holder").masonry({
itemSelector: '.shout'
})
// );
});
}
}
});
directive template is
<div id="shout-content-holder">
<div class="shout" ng-repeat="shout in shouts">
<p>{{shout.message}}</p>
<img src="media/images/delete.png" width="32" height="32" ng-click="deleteShout()"/>
</div>
</div>
i load the shouts from a webservice. please help me to make this work...
Putting what I mentioned in comment as an answer. This could actually be done using a template rather than using .append() , it would be cleaner. What you'd need is a template to contain a list of columns and ng-repeat, should work just as well, but you'd have to wait for the first item to get inserted before you calculate where to insert the second item; hence the use of .append() here.
.directive('columns', function(){
return {
restrict: 'E',
scope: {
itemList: '=', // a list of items
colCount: "#" // number of columns
},
link: function(scope, elm, attrs) {
//console.log(scope.itemList);
var numCols = parseInt(scope.colCount);
var colsArr = [];
for(var i=0; i< numCols; i++){
colsArr.push(angular.element("<div class='column' style='width:"+(100/numCols -.5)+"%' >Col "+(i+1)+"</div>"));
elm.append(colsArr[i]);
}
angular.forEach(scope.itemList, function(value, key){
var item = angular.element("<div class='item' style='height:"+value.height+"px; background:"+'#'+Math.floor(Math.random()*16777215).toString(16)+"'>"+value.value+"</div>");
var smallestColumn = getSmallestColumn();
angular.element(smallestColumn).append(item);
});
function getSmallestColumn(){
var smallestHeight = colsArr[0][0].offsetHeight;
var smallestColumn = colsArr[0][0];
angular.forEach(colsArr, function(column, key){
if(column[0].offsetHeight < smallestHeight){
smallestHeight = column[0].offsetHeight;
smallestColumn = colsArr[key];
}
});
return smallestColumn;
}
}
};
});
plnkr.co/edit/UyRS0clrCwDpSrYgBsXS?p=preview
You probably want to trigger your masonry() call on the $last ng-repeat instead of using $watch. I just recently answered a question about this, so I will refer you there: https://stackoverflow.com/a/14656888/215945

Resources