ng-click and ngRouting on mobile devices - iphone

I am completely new to Angularjs and haven’t been doing any code for ages. I started setting up my website again with Angularjs. I have a main page and an about page, to which the user gets via ngRoute on ng-click (or hitting space). Once on the about page, the user can go back by clicking somewhere on the page and so on.
App.js
var app = angular.module("MyApp", ["ngRoute"]);
app.config(function($locationProvider, $routeProvider) {
$routeProvider
.when("/teaser", {
controller:"teaserCtrl",
templateUrl:'teaser.html'
})
.when("/about", {
controller:"aboutCtrl",
templateUrl: "about.html"
})
.otherwise({
redirectTo:"/teaser"
})
});
app.controller("mainCtrl", function($scope, $http, $location) {
$scope.v = {
inverted: false,
display: true,
offwhite: true,
}
$scope.$on("space", function() {
if ($scope.v.teaser) {
$location.path("/about")
$scope.v.teaser = false
} else {
$location.path("/teaser")
$scope.v.teaser = true
}
$scope.$apply()
})
$scope.goHome = function(){
$scope.$broadcast("goHome")
}
});
app.directive("ngMobileClick", [function () {
return function (scope, clickElement, attrs) {
clickElement.bind("touchstart click", function (e) {
e.preventDefault();
e.stopPropagation();
scope.$apply(attrs["ngMobileClick"]);
});
}
}])
HTML
<body ng-controller="mainCtrl as main" ng-mobile-click="goHome()" ng-class="{inverted: v.inverted, bg: v.offwhite}" space>
<div class="content" ng-view ng-hide="v.display"></div>
//My body code
<script ng-init="sw = 'some website'; id="about.html" type="text/ng-template">
<div class="about">
<p class="text" ng-click="next(); $event.stopPropagation()">
<p>some text</p>
<br>
<a ng-href="{{mail}}" ng-click="$event.stopPropagation()">some address</a>
</p>
</div>
</script>
</body>
The code for the about page is written into a script and it has hyperlinks (ng-href). Now my issue: As you can see, I changed my ng-click to ng-mobile-click for the body-section. If I also change it in the script for the hyperlinks, something weird is happening which I can’t really figure out (links change to hover color, but still no redirection to the ng-href.
For the desktop version, the click is triggering ngRoute, but I can also click the links. For the mobile version this is not possible any more. Any ideas how I can fix this? I know, there is no hovering possible, but somehow I need to detect the hyperlinks also on mobile devices without being redirected to the main-page.
As I said: this is my first try with Angularjs and I haven’t done any code for a while, please be as clear as possible!
There is another controller for teaser/about which I haven’t put here, as well as the directive for the keyup.
Any ideas or suggestions? Thank you so much in advance!

Related

Facebook Login Button not appearing in ui-view child

I'm making an AngularJS app with the facebook sdk. The structure comes as follows:
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<title>Reportes para Anunciantes</title>
<meta charset="UTF-8">
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-ui-router.min.js"></script>
<!-- more scripts here -->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'MYAPPID', //Have an actual app id in my source
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.0' // use version 2.0
});
angular.bootstrap(document, ['Application']);
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/es_LA/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="content" ui-view>
Cargando API de Facebook ...
</div>
</body>
</html>
In the page, I load Angular once the Facebook API is loaded. The site uses xfbml for the login buttons.
The whole angular app is in index.js:
var Application = angular.module(
"Application",
['ui.router'],
['$stateProvider', function($stateProvider){
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$stateProvider
.state('notloggedin', {
templateUrl: 'templates/notloggedin.html',
controller: 'Application.NotLoggedIn'
})
.state('notauthorized', {
templateUrl: 'templates/notauthorized.html',
controller: 'Application.NotAuthorized'
})
.state('inapp', {
templateUrl: 'templates/inapp.html',
controller: 'Application.InApp'
});
}]
);
function FBStatusChecker($state){
this._state = $state;
}
FBStatusChecker.prototype = {
checkAndGo: function(response) { /* omitted - no issue here */ },
/* omitted methods - no issue here */
updateState: function(){
var context = this;
FB.getLoginStatus(function(response) {
context.checkAndGo(response);
})
}
};
Application.StatusChangeService = Application.service('Application.FBStatusChecker', ['$state', FBStatusChecker]);
Application.directive("fbLoginButton", function() {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
console.log("your ass");
if (FB) {
console.log("is broken");
FB.XFBML.parse(iElement[0]);
}
}
}
});
/* omitted controllers - no issue here.
two of them are empty, and one correctly updates the scope
via $scope.$apply(...) for an asynchronous callback */
Application.run(['Application.FBStatusChecker', function(statusChecker){
statusChecker.updateState();
}]);
Let's analyze by parts:
The page uses ui-router to switch between application states. This works as expected. Angular is only loaded (i.e. my module being run) once the FB API was successfully loaded.
The application defines three states, and in run() one of those states is selected.
I omitted the controllers, since two are empty, and the third updates -with no issues- the scope.
I omitted the state-switcher service methods (this has the task to use $state to switch to one of three states depending on facebook state).
There's a directive named fbLoginButton. This directive must be recognized as 'E' (lement), and should match fb:login-button. The directive is successfully matched.
I had no issue generating the button before using AngularJS and ui-router.
Finally, the templates come:
notloggedin.html
<fb:login-button max_rows="1" size="xlarge" show_faces="false" auto_logout_link="false"></fb:login-button>
Debes iniciar sesión en Facebook para continuar.
notauthorized.html
<fb:login-button max_rows="1" size="xlarge" show_faces="false" auto_logout_link="false"></fb:login-button>
Debes autorizar la aplicación para continuar.
inapp.html
<span ng-if="name">
Bienvenido {{ name }}!
</span>
<span ng-if="!name">
Listando ...
</span>
Notes: Also tried HTML5 solution, using div, instead of xfbml.
And my issue is: The facebook buttons are not being shown. Only the corresponding texts are being shown. If i'm logged in Facebook when I hit this page, I get correctly redirected to the expected state, with the {{ name }} being fetched. The same occurs with the other states, so I'm not having issue specificly with graph api, but with xfbml.
And my question is: What am I missing? The directive is being matched but seems that FM.XML.parse has no effect. How can I fix it?
Apparently -discovered it by a lucky mistake- the .parse method ignores the current element, so the parse must start from the parent element. So far, the directive must be changed to:
Application.directive("fbLoginButton", function() {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
if (FB) {
FB.XFBML.parse(iElement[0].parent);
}
}
}
});
which consisted in just adding the .parent property to get the parent DOM node.
However, if two items matched by this directive are siblings (or using another directive with the same functionality), this could be run twice. So recording the element in an array after parsing it, and checking before parsing it, would be a good workaround to avoid doing the parsing twice. Another alternative would be to force a parsing in each state's controller, to the ui-view-holding container. The latter would be implemented like this:
The only directive will be an attribute-based directive, e.g. xfbml-parse in the ui-view element (in my case):
Application.directive("fbLoginButton", function() {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
if (FB) {
FB.XFBML.parse(iElement[0].parent);
}
}
}
});
being no need to implement other directives.
After that, use xfbml-parse directive in the ui-view element. In my case:
<div id="content" ui-view xfbml-parse>
Cargando API de Facebook ...
</div>
which will run the link function every time the state changes.
So: every time the ui-view node renders, the XFBML will be parsed.

AngularJS ignores form submit

I'm using AngularJS v1.2.13 to create a page with a form which will download a user's file on click.
I'm using $sce to enable the injection of the file URL which works fine.
However, the loading of the resource disables the form submit. I'm sure it has to do with the resource load because when I remove the load and hardcode the url it works fine. I've also created a JSFiddle without it and have not been able to reproduce the problem there.
Any ideas on why this is happening and how it can be fixed?
HTML:
<div ng-controller="viewProfileController" data-ng-init="findOne();">
<form method="get" action="{{downloadFileURL}}">
<button type="submit" class="no-button comment-small" >
Download File
</button>
</form>
</div>
Controller:
'use strict';
angular.module('bop.viewProfile').controller('viewProfileController', [
'$scope', 'Users', '$sce', '$routeParams',
function($scope, Users, $sce, $routeParams) {
$scope.downloadFileURL = '';
// Find current user
$scope.findOne = function() {
Users.get({
userId: $routeParams.userId
}, function(user) {
$scope.user = user;
$scope.downloadFileURL = $sce.trustAsResourceUrl($scope.user.file.url);
});
};
}]);
Users Service:
var userServices = angular.module('bop.users', ['ngResource']);
userServices.factory('Users', ['$resource', function($resource) {
return $resource(
'users/:userId',
{ userId: '#_id' },
{ update: { method: 'PUT' } }
);
}]);

When clicking on login with facebook/persona button with angularFire v0.5.0 ($firebaseAuth) user gets redirected immediately to '/'.Why?

My problem is simple, everything in this code works as expected except that everytime, I click on login button, I get redirected to '/'. I do not want that. I want the user to stay on login page until they finish authenticating via facebook/persona/twitter and then get redirected to '/content'.
Here is my router/app/controllers:
var app = angular.module("myapp", ["ngRoute","firebase"]);
app.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/',{
templateUrl: 'landing.html',
});
$routeProvider.when('/login',{
templateUrl: 'login.html',
controller: 'controller'
});
$routeProvider.when('/content',{
authRequired: true,
templateUrl: 'content.html',
controller: 'MyController'
});
$routeProvider.otherwise({redirectTo: '/'});
}]);
app.controller('MyController',['$scope', '$firebase','$firebaseAuth',function($scope,$firebase,$firebaseAuth) {
var ref = new Firebase("https://mybase.firebaseio.com/");
$scope.auth = $firebaseAuth(ref,{path: '/'});
$scope.messages = $firebase(ref);
$scope.addMessage = function(e) {
if (e.keyCode != 13) return;
$scope.messages.$add({from: $scope.name, body: $scope.msg});
$scope.msg = "";
};
}]);
app.controller('controller',['$scope','$firebaseAuth',function($scope, $firebaseAuth) {
var ref = new Firebase('https://mybase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref);
}]);
This (my preferred solution) didnt work either:
.controller('LoginCtrl',['$scope','$firebase','$firebaseAuth','$location',function($scope,$firebase,$firebaseAuth,$location, waitForAuth){
var ref = new Firebase('https://myfirebase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref,{path: '/'});
waitForAuth.then(function(user){
$location.path('/content');
})
}])
My div/button looks as follows (I also have similar one but with 'persona'.):
<div ng-controller="controller">
<div class="facebook-login">
<span><i class="fa fa-facebook-square fa-lg"></i> LogIn with Facebook</span>
</div>
<div class="facebook-login">
<span><i class="fa fa-facebook-square fa-lg"></i> LogIn with Persona</span>
</div>
</div>
I have included the following in my html:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="//cdn.firebase.com/v0/firebase.js"></script>
<script src="//cdn.firebase.com/v0/firebase-simple-login.js"></script>
<script src="//cdn.firebase.com/libs/angularfire/0.5.0/angularfire.min.js"></script>
<script src="//code.angularjs.org/1.2.6/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/module.waitForAuth.js"></script>
<script src="//login.persona.org/include.js"></script>
<script src="app.js"></script>
I have enabled facebook login and persona login in my firebase forge. Also I have added my facebook app id and secret too. Everytime I click on the login button I get redirected to '/'. waitforAuth I use is here: https://gist.github.com/katowulf/7328023, but if I use it in my controllers, login with facebook/persona buttons do not work at all. If I use waitForAuth, everytime I click on one of the login buttons I get redirected to '/' immediately instead of login popup.
Anyone? :)
I finally found the solution to my problem. Adding the following stops automatic redirect to '/' before login even takes place:
I just needed to add this:
$scope.$on('$locationChangeStart', function(event) {
event.preventDefault();
});
In here like this:
app.controller('controller',['$scope','$firebaseAuth','$location','$rootScope',function($scope, $firebaseAuth,$location,$rootScope) {
$scope.$on('$locationChangeStart', function(event) {
event.preventDefault();
});
var ref = new Firebase('https://mybase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref);
$rootScope.$on('$firebaseAuth:login', function(){
$location.path('/content');
});
}]);
However, I ran into another problem, because this now doesnt work:
$rootScope.$on('$firebaseAuth:login', function(){
$location.path('/content');
Because after user is finished authenticating they should be redirected to /content (instead of being stuck at login page with login buttons disappearing due to ng-hide (See above)), but it does not matter what I try $location.path('/content') doesnt work.
I tried this:
waitForAuth.then(function(){
console.log('test');
$location.path('/content');
})
But console.log prints out "test" in the console way before user is authenticated, so waitForAuth doesnt seem to work either :/. Somehow waitForAuth fires console.log but it doesnt fire $location.path... Odd.
I even tried doing this (both with waitForAuth and $rootScope.$on:
waitForAuth.then(function(){
console.log('test');
$location.path('/content');
$scope.$apply();
})
But I just get an error that angular $digest is already in progress.
Adding this: ng-click="auth.$login('facebook'); return false;" like that, angular throws me this error :
Error: [$parse:syntax] Syntax Error: Token 'false' is an unexpected token at column 33 of the expression [auth.$login('facebook'); return false;] starting at [false;].
And login buttons become un-clickable... :(
Ohh dear... me :)
I had the same problem where the URL was always reverting back to the homepage. The problem was caused by a simple mistake in the html syntax:
Log out
After I removed # in the href attribute the problem was resolved. Hope this helps others who may experience a similar problem.

Tipsy tooltip script does not work with Ajax

I use Tipsy tooltip script on my website:
Script homepage and examples
See the script
It displays some information on mouseover. For example, I have a page with users photos (thumbnails) and onmouseover Tipsy displays user name and age.
<div id="up_gus" style="display:inline-block;">
<a href="/profile.php"><img class="west" title="username showed by Tipsy" src="/foto.jpg"/>
</a></div
It works fine, but now I added Ajax/Jquery to load more photos without page refresh.
<div id="more"><a class="l_more" id="<?php echo $pid;?>" href="#!" >Show more</a></div>
$('.l_more').live("click",function() {
var last_msg_id = $(this).attr("id");
if(last_msg_id!='end'){
$.ajax({
type: "POST",
url: "/mas.php",
data: "vid="+ last_msg_id,
beforeSend: function() {
$('a.l_more').append('<img src="../load.gif" />');
},
success: function(html){
$("div#more").remove();
$("div#up_gus").append(html);
}
});
}
return false;
});
If I load more results (photos) Tipsy onmouseover does not display anything. Any ideas whi it does not work with Ajax?

Customize google cloud print button function

Currently i am using the google cloudprint button for my site
<script src="//www.google.com/cloudprint/client/cpgadget.js"></script>
<script defer="defer">
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(document.getElementById("custom_print_button"));
gadget.setPrintDocument("url", "Cloud Print test page",
"http://www.google.com/cloudprint/learn/");
</script>
I want to send an email when I hit the print button, is this possible?
No problem at all... just attach an onclick handler to the print button, or bind the click with jQuery and call a function to do your email. I used it to create a document with Ajax before it was printed:
<script>
function printIT() {
jQuery.ajax({
url: "print_this.php",
context: document.body,
success: function(responseText) {
alert("Document sent!");
return false;
}
});
}
</script>
<button id="print_button_container" class="ui-link" onclick="printIT();"></button>
<script src="//www.google.com/cloudprint/client/cpgadget.js">
</script>
<script defer="defer">
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(document.getElementById("print_button_container"));
gadget.setPrintDocument("url", "My Document", "http://www.yourpath.com/yourdoc.html");
</script>
Simplified version... not tested but should work :)