angularjs socials share buttons troubles the display is only in one page - facebook

I'm going mad with a simple embedded of social buttons.
Put it in this way I've got two states home and blog
with this code
home
<div id="socials-bar" class=" clearfix">
<ul class="pull-right">
<li>
<div class="fb-like" data-href="http://mydomain.com" data-layout="standard" data-action="like" data-show-faces="false" data-share="true"></div>
</li>
<li>
Tweet
</li>
<li>
<div class="g-plusone" data-size="small" data-annotation="inline" data-width="120" data-href="http://mydomain.it"></div>
</li>
</ul>
</div>
//other html
<script>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
</script>
<script>
window.___gcfg = {lang: 'it'};
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
blog
<div class="clearfix">
<ul class="article-socials pull-right">
<li>
<div class="fb-like" data-href="http://mydomain.it/blog/{{article.id}}/{{article.slug}}" data-layout="standard" data-action="like" data-show-faces="false" data-share="true"></div>
</li>
<li>
Tweet
</li>
<li>
<div class="g-plusone" data-size="small" data-annotation="inline" data-width="120" data-href="http://mydomain.it/blog/{{article.id}}/{{article.slug}}"></div>
</li>
</ul>
</div>
<script>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
</script>
<script>
window.___gcfg = {lang: 'it'};
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
The problem is that the I see them only in the home
page if I get rid off of them in home I can see them in the blog state
Do you know what could be the problem ?

UPDATE: I've updated the below directives and registered them on bower with the package name 'angulike', for full details and a working demo go to http://jasonwatmore.com/post/2014/08/01/AngularJS-directives-for-social-sharing-buttons-Facebook-Like-GooglePlus-Twitter-and-Pinterest.aspx
The problem is that the social buttons only get initialized on page load by default, so in an angularjs app you need to re-initialize the buttons yourself when the view changes. I got them working by creating a directive for each, below is the code:
Google Plus Button Directive
app.directive('googlePlus', ['$window', function ($window) {
return {
restrict: 'A',
template: '<div class="g-plusone" data-size="medium"></div>',
link: function (scope, element, attrs) {
scope.$watch(function () { return !!$window.gapi; },
function (gapiIsReady) {
if (gapiIsReady) {
$window.gapi.plusone.go(element.parent()[0]);
}
});
}
};
}]);
Tweet Button Directive
app.directive('tweet', ['$window', function ($window) {
return {
restrict: 'A',
template: 'Tweet',
link: function (scope, element, attrs) {
scope.$watch(function () { return !!$window.twttr; },
function (twttrIsReady) {
if (twttrIsReady) {
$window.twttr.widgets.load(element.parent()[0]);
}
});
}
};
}]);
Facebook Like Button Directive
app.directive('fbLike', ['$window', function ($window) {
return {
restrict: 'A',
template: '<div class="fb-like" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></div>',
link: function (scope, element, attrs) {
scope.$watch(function () { return !!$window.FB; },
function (fbIsReady) {
if (fbIsReady) {
$window.FB.XFBML.parse(element.parent()[0]);
}
});
}
};
}]);
HTML to use the directives
<div data-fb-like=""></div>
<div data-tweet=""></div>
<div data-google-plus=""></div>

If I understand, probably you should remove the script in blog state template.
Anyway, I can share how I do in my sample project:
index.html
directive for social buttons
template for
social buttons
basically in index there are scripts for social buttons available for all states

Related

Bigcommerce redirect on cart page

Adding custom script into my cart.html file in bigcommerce to include a script that will redirect card holder to google.com when they click checkout (only going to google for now while testing script)
When the script is loaded I see the following error in the console (self.checkoutButton.on is not a function)
Here is the script + file
cart: true
<script>
document.addEventListener("DOMContentLoaded", function () {
var debug = true ? console.log.bind(console, '[DEBUG][Cart]') : function () {};
debug('Script loaded');
window.Cart = function (options) {
var self = {}
function init() {
self.options = Object.assign({
checkoutButtonSelector: document.getElementById("checkout"),
checkoutUrl: 'https://google.com',
}, options);
self.checkoutButton = (self.options.checkoutButtonSelector);
debug('Initialized with options', self.options);
inject();
}
function inject() {
debug('Inject');
self.checkoutButton.on('click', checkout);
}
function checkout(event) {
var checkoutUrl = getCheckoutURL(self.options.products);
debug('Checkout ->', checkoutUrl);
event.preventDefault();
window.location.href = checkoutUrl;
}
function getCartCookie(name) {
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match){
return match[2];
}
}
function getCheckoutURL(products) {
cookie = getCartCookie('cart');
var urlLineItems = Object.keys(products).reduce(function (output, productId) {
var quantity = products[productId];
return output.concat([ productId + ':' + quantity ]);
}, []).join(';');
return self.options.checkoutUrl + '?products=' + urlLineItems + '&cartId='+cookie;
}
init();
return self;
};
var instance = new Cart();
});
</script>
<div class="page">
<main class="page-content" data-cart>
{{> components/common/breadcrumbs breadcrumbs=breadcrumbs}}
{{> components/cart/page-title}}
<div data-cart-status>
{{> components/cart/status-messages}}
</div>
{{#if cart.items.length}}
<div class="loadingOverlay"></div>
<div data-cart-content class="cart-content-padding-right">
{{> components/cart/content}}
</div>
<div data-cart-totals class="cart-content-padding-right">
{{> components/cart/totals}}
</div>
{{#if cart.show_primary_checkout_button}}
<div class="cart-actions cart-content-padding-right">
<a class="button button--primary" id='checkout' title="{{lang 'cart.checkout.title'}}">{{lang 'cart.checkout.button'}}</a>
{{#if cart.show_multiple_address_shipping}}
<a class="checkoutMultiple" href="{{urls.checkout.multiple_address}}">
{{lang 'cart.preview.checkout_multiple'}}
</a>
{{/if}}
</div>
{{else}}
<div class="cart-actions cart-content-padding-right">
<a class="button" href="{{urls.home}}" title="{{lang 'cart.continue_shopping'}}">{{lang 'cart.continue_shopping'}}</a>
</div>
{{/if}}
{{#if cart.additional_checkout_buttons}}
<div class="cart-additionalCheckoutButtons cart-content-padding-right">
{{#each cart.additional_checkout_buttons}}
{{{this}}}
{{/each}}
</div>
{{/if}}
{{else}}
<h3 tabindex="0">{{lang 'cart.checkout.empty_cart'}}</h3>
{{/if}}
</main>
</div>
{{/partial}}
{{> layout/base}}
Would you have any idea why I would be getting the following error? Thanks in advance
You are using .on which is a JQuery function. You’re not using JQuery to wrap your selector, you’re just using the vanilla JS getElementById. You need to use a vanilla JS function to add the event, such as addEventListener.

angularfire and facebook login getting Cannot read property 'onAuth' of undefined

Hi i found a sample of auth on routing with angularfire, i just change it to support the new firebase sdk v4 and still using angularfire v1.
this is the link of the piece of code i used (with ui-router) :
angularfire docs
now this is my app.js and index.html
var config = {
"apiKey": "AIzaSyAUoM0RYqF1-wHI_kYV_8LKgIwxmBEweZ8",
"authDomain": "clubears-156821.firebaseapp.com",
"databaseURL": "https://clubears-156821.firebaseio.com",
"projectId": "clubears-156821",
"storageBucket": "clubears-156821.appspot.com",
"messagingSenderId": "970903539685"
};
firebase.initializeApp(config);
var app = angular.module("sampleApp", [
"firebase",
"ui.router"
]);
app.factory("Auth", ["$firebaseAuth",
function ($firebaseAuth) {
return $firebaseAuth();
}
]);
// UI.ROUTER STUFF
app.run(["$rootScope", "$state", function ($rootScope, $state) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go("home");
}
});
}]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
template: "<h1>Home</h1><p>This is the Home page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$waitForAuth();
}]
}
})
.state('profile', {
url: "/profile",
template: "<h1>Profile</h1><p>This is the Profile page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$requireSignIn();
}]
}
})
});
app.controller("MainCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
console.log(authData);
});
}
]);
app.controller("NavCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
});
}
]);
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
</head>
<body>
<div ng-app="sampleApp">
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default navbar-static-top" ng-controller="NavCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ui-sref-active="active">
<a ui-sref="home" href="#">Home</a>
</li>
<li ui-sref-active="active" ng-show="authData">
<a ui-sref="profile" href="#">
My Profile
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-hide="authData">
<a href="#" ng-click="$parent.auth.$authWithOAuthPopup('facebook')">
<span class="fa fa-facebook-official"></span>
Sign In with Facebook
</a>
</li>
<li ng-show="authData">
<a href="#" ng-click="$parent.auth.$unauth()">
<span class="fa fa-sign-out"></span>
Logout
</a>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div ui-view ng-show="authData"></div>
<div class="login-screen" ng-hide="authData">
<div class="jumbotron text-center">
<h1>Sweet login, brah.</h1>
<p class="lead">This is a pretty simple login utilizing AngularJS and AngularFire.</p>
<button class="btn btn-primary btn-lg" ng-click="auth.$authWithOAuthPopup('facebook')">
<span class="fa fa-facebook-official fa-fw"></span>
Sign in with Facebook
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="app.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.3/angularfire.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
</body>
</html>
now the problem is that i getting an error : Cannot read property 'onAuth' of undefined.
i think its problem of the version of the new SDk and i looked in the proposed solution here in stackoverflow but none of them fix me the problem.
please help...
Ok i figure out the problem and fix it by changing the versions of angular and angularfire. and a little change to migrate to the new sdk.
this is new code.
my problem now is that i don't get all the scope that i want from facebook. for example i want birthday and i cannot see it comes back.
someone have a suggestion ?
var config = {
"apiKey": "AIzaSyAUoM0RYqF1-wHI_kYV_8LKgIwxmBEweZ8",
"authDomain": "clubears-156821.firebaseapp.com",
"databaseURL": "https://clubears-156821.firebaseio.com",
"projectId": "clubears-156821",
"storageBucket": "clubears-156821.appspot.com",
"messagingSenderId": "970903539685"
};
firebase.initializeApp(config);
var app = angular.module("sampleApp", [
"firebase",
"ui.router"
]);
app.factory("Auth", ["$firebaseAuth",
function ($firebaseAuth) {
return $firebaseAuth();
}
]);
//var provider = Auth.FacebookAuthProvider();
//provider.addScope('user_birthday');
//
//Auth.signInWithRedirect(provider);
// UI.ROUTER STUFF
app.run(["$rootScope", "$state", function ($rootScope, $state) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go("home");
}
});
}]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
template: "<h1>Home</h1><p>This is the Home page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$waitForSignIn();
}]
}
})
.state('profile', {
url: "/profile",
template: "<h1>Profile</h1><p>This is the Profile page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$requireSignIn();
}]
}
});
});
app.controller("MainCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuthStateChanged(function (authData) {
$scope.authData = authData;
console.log(authData);
});
}
]);
app.controller("NavCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.currentUser = null;
$scope.currentUserRef = null;
$scope.currentLocation = null;
$scope.auth = Auth;
console.log(Auth);
/**
* Function called when clicking the Login/Logout button.
*/
// [START buttoncallback]
$scope.SignIn = function () {
if (!Auth.currentUser) {
$scope.auth.$signInWithRedirect('facebook', {
scope: 'email, public_profile, user_birthday'
}).then(function (authData) {
// never come here handle in $onAuthStateChanged because using redirect method
}).catch(function (error) {
if (error.code === 'TRANSPORT_UNAVAILABLE') {
$scope.$signInWithPopup('facebook', {
scope: 'email, public_profile, user_friends'
}).catch(function (error) {
console.error('login error: ', error);
});
} else {
console.error('login error: ', error);
}
});
} else {
// [START signout]
Auth.signOut();
// [END signout]
}
};
// [END buttoncallback]
//
// $scope.updateUserData = function () {
// $scope.currentUserRef.set($scope.currentUser);
// };
$scope.auth.$onAuthStateChanged(function (authData) {
$scope.authData = authData;
console.log('after login');
console.log($scope.authData);
});
}
]);
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<div ng-app="sampleApp">
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default navbar-static-top" ng-controller="NavCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ui-sref-active="active">
<a ui-sref="home" href="#">Home</a>
</li>
<li ui-sref-active="active" ng-show="authData">
<a ui-sref="profile" href="#">
My Profile
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-hide="authData">
<a href="#" ng-click="SignIn()">
<span class="fa fa-facebook-official"></span>
Sign In with Facebook
</a>
</li>
<li ng-show="authData">
<a href="#" ng-click="SignIn()">
<span class="fa fa-sign-out"></span>
Logout
</a>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div ui-view ng-show="authData"></div>
<div class="login-screen" ng-hide="authData">
<div class="jumbotron text-center">
<h1>Sweet login, brah.</h1>
<p class="lead">This is a pretty simple login utilizing AngularJS and AngularFire.</p>
<button class="btn btn-primary btn-lg" ng-click="SignIn()">
<span class="fa fa-facebook-official fa-fw"></span>
Sign in with Facebook
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="app.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
</body>
</html>

Ionic - show splash screen until the first image loads

I have an app in Ionic v.1 and on page where I have a list of articles, I would like to have a splash screen until the first image is completely loaded, not sure how to do that?
This is the controller:
module.exports = angular.module('coop.controllers')
.controller('ArticlesController', function($scope, ArticleService, $state, $ionicScrollDelegate, $location, $ionicPosition, $ionicConfig) {
$scope.articles = ArticleService.all();
$scope.$on('$ionicParentView.afterEnter', function(event, data) {
$scope.videoPlaying = [];
$ionicConfig.views.swipeBackEnabled(false);
if (data.direction == 'back') {
$scope.doRefresh();
}
});
$scope.articleType = 'all';
$scope.articleFilter = function(button) {
$scope.articleType = button;
$scope.doRefresh();
};
$scope.showBulletPoint = function(which) {
return $scope.articleType == which;
}
$scope.like = function(article){
article.userLiked = !article.userLiked;
ArticleService.like(article)
};
$scope.doRefresh = function (){
var articleType = $scope.articleType ? $scope.articleType : 'all';
ArticleService[articleType]().$promise.then(function(data){
$scope.articles = data;
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.videoPlaying = [];
$scope.playerVars = {
controls: 0,
showinfo: 0
};
$scope.playVideo = function(youtubePlayer, index) {
$scope.videoPlaying[index] = true;
youtubePlayer.playVideo();
};
$scope.$on('$ionicView.afterLeave', function(event, data) {
$scope.videoPlaying = false;
$ionicConfig.views.swipeBackEnabled(true);
//youtubePlayer.stopVideo();
});
});
And this the html:
<ion-view>
<div class="row articles-header">
<button menu-toggle="left" class="button button-icon icon ion-navicon-round"></button>
<div class="right-icons">
<!--<a class="button button-icon icon ion-ios-search-strong">
</a>-->
<a class="button button-icon" href="#" ng-click="articleFilter('all')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('all')"></i> Siste
</a>
<a class="button button-icon" href="#" ng-click="articleFilter('video')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('video')"></i> Video
</a>
<a class="button button-icon" href="#" ng-click="articleFilter('popular')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('popular')"></i> Populært
</a>
</div>
</div>
<ion-content class="articles-content">
<ion-refresher pulling-icon="false" on-refresh="doRefresh()">
</ion-refresher>
<ion-list>
<ion-item ng-repeat="article in articles" class="item-light">
<div class="article">
<a ng-if="authenticated" ng-show="article.external_media.length == 0" ui-sref="main.article({id: article.id})" nav-direction="forward" class="article-image-link">
<img class="img" src="{{ fileServer }}/imagecache/cover/{{article.cover_image}}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
</a>
<a ng-if="!authenticated" ng-show="article.external_media.length == 0" ui-sref="main.articlePublic({id: article.id})" nav-direction="forward" class="article-image-link">
<img class="img" src="{{ fileServer }}/imagecache/cover/{{article.cover_image}}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
</a>
<a ui-sref="main.article({id: article.id})">
<div class="iframe" ng-show="article.external_media.length > 0 && article.external_media.image != ''">
<img class="img" ng-src="{{ article.external_media[0].image }}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
<div class="iframe-overlay">
<div class="play">
<img class="playButton" src="icons/playRectangle.svg"/>
</div>
</div>
</div>
</a>
</div>
<div class="row article-meta" ng-class="{ 'has-comments': article.enable_comments }">
<a ng-click="like(article)" class="subdued col col-30">
<img class="social-images" ng-src="icons/{{ article.userLiked ? 'heart' : 'heart-outline' }}.svg"/> Lik
</a>
<a ui-sref="main.article({id: article.id, gotoComments: true })" class="subdued col col-60" ng-if="article.enable_comments">
<img class="social-images" src="icons/comment.svg"/> {{ article.commentCount }} Kommentarer
</a>
<a ui-sref="main.article({id: article.id})" nav-direction="forward" class="col col-10 article-link right">
<img class="social-images" src="icons/arrow.svg"/>
</a>
</div>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
One approach is to attach an onLoad handler to the images, and when the first image (or any other specific image, all, etc) have loaded you can remove your splash screen.
To do this we'll create a directive to handle the onload event, based on this outstanding solution from Peter, combined with the $ionicLoading loader.
var app = angular.module('app', ['ionic'])
app.controller('appCtrl', function($scope, $timeout, $ionicLoading) {
// Setup the loader
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
// Add a simple onLoad callback
$scope.onLoad = function (id) {
if (id === 0) {
$ionicLoading.hide();
}
}
$scope.items = [
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'},
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'},
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'}
];
});
// The imageonload directive
app.directive('imageonload', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
//call the function that was passed
scope.$apply(attrs.imageonload);
});
}
};
})
Then use the directive:
<ion-item ng-repeat="item in items" href="#">
<img ng-src="{{item.img}}" imageonload="onLoad({{$index}})" id="img-{{$index}}" />
</ion-item>
When the app loads the $ionicLoading screen will be shown until the first image emits the onload event, causing the $ionicLoading screen to be removed.
For a working demo, see this Ionic Play demo.
The loading screen may only be noticeable the first time you load the demo, and on subsequent loads you might need to do a hard refresh.

angularjs fb like don't render value

I've a strange behavior with this code
.controller('ContestantCreateCtrl',function($scope,CONFIG) {
$scope.shareurl = 'https:'+CONFIG.site.absoluteUrl+'/';
})
.directive('btFbParse', function () {
return {
restrict:'A',
link:function (scope, element, attrs) {
console.log(scope.shareurl);//it works
if(scope.facebookIsReady){
FB.XFBML.parse();
}
}
};
})
if in the view I set up
<div class="fb-like" data-href="https://my-dev.me/public/" data-width="120" data-colorscheme="light" data-layout="standard" data-action="like" data-show-faces="true" data-send="false"></div>
<div bt-fb-parse></div>
it works
but if in the view I set up
<div class="fb-like" data-href="{{shareurl}}" data-width="120" data-colorscheme="light" data-layout="standard" data-action="like" data-show-faces="true" data-send="false"></div>
<div bt-fb-parse></div>
I get form facebook api
"/plugins/error/api?code=100&message=The+href+URL+must+be+absolute&hash=AQDVWDuDsG3_aVQh
I tried also with
scope.$apply()
in the directive the fb like works but angular show me
a Error: $digest already in progress
I don't know which way to turn ....
Update
with
_.defer(function(){
scope.$apply();
FB.XFBML.parse();
});
it works :)
thanks to https://stackoverflow.com/a/17958847/356380

rendering fb-like buttons with knockoutjs

My page contains list of posts, each post has its own like button. The posts are JSON-ly retrieved from the server. Each like should have ofcourse its own href, which is part of the post json object. So naturally I'd expect this to work (assuming "fb_data"
is json object {fb_data: {href: my_post_path}):
(html fb-like widget code, with simple knockoutjs data-bind)
<li class="fb">
<div class="fb-like" data-send="false" data-layout="button_count" data-width="85" ata-show-faces="false" data-bind="attr: {href: fb_data.href}"></div>
<span class="like-container"><span class="likebox" title=""></span> Friends<br/>Like this!</span>
</li>
so that didn't work.
I tried another approach and implemented custom binding for that purpose:
(html)
<li class="fb">
<div class="fb-like" data-send="false" data-layout="button_count" data-width="85" data-show-faces="false" data-bind="render_like: fb_data"></div>
<span class="like-container"><span class="likebox" title=""></ span> Friends<br/>Like this!</span>
</li>
(js)
ko.bindingHandlers.render_like = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var fb = valueAccessor();
$(element).attr(fb);
FB.XFBML.parse(element);
}
};
ok, that didn't work either. I turn to the hard, ugly, not elegant way and had this:
(html)
<li class="fb" data-bind="render_like: fb_data"></li>
(js)
ko.bindingHandlers.render_like = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var fb = valueAccessor();
var fb_like_str = '<div class="fb-like" data-send="false" data layout="button_count" data-width="85" data-show-faces="false"' href="' + fb.href + '" </div>';
fb_like_str += '<span class="like-container"><span class="likebox" title=""></span> Friends<br/>Like this!</span>';
$(element).html(fb_like_str);
FB.XFBML.parse(element);
}
};
that one worked, but it doesn't feel like the knockout spirit ... what
is the problem with the first 2??
OK, I think I've just figured out what the problem was. Initiating my viewModel should come after FB.init, like that -
window.fbAsyncInit = function() {
FB.init({appId: 172535899504455, status: true, cookie: true, xfbml: true});
var myVM = new myViewModel(rec_data, $("#myselector").get(0));
}
now the nice easy first way is working!