$window.location.href NOT WORKING in AngularJS - html

I'm building a basic AngularJS Login page and the $window.location.href did not re-direct the page to a new html in my system, hosted by WAMP. I even tried re-directing it to google. Nothing happens. I tried all the available solutions here and nothing seems to work. Any solutions ?
JS followed by HTML
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.submit = function() {
if ($scope.username && $scope.password) {
var user = $scope.username;
var pass = $scope.password;
if (pass == "admin" && user == "admin#admin.com") {
alert("Login Successful");
$window.location.href = "http://google.com"; //Re-direction to some page
} else if (user != "admin#admin.com") {
alert("Invalid username");
} else if (pass != "admin" && user == "admin#admin.com") {
alert("Invalid password");
}
} else {
alert("Invalid Login");
}
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="login.js"></script>
<link rel="stylesheet" href="login.css">
</head>
<body ng-controller="MainCtrl">
<form>
<label>Username:</label>
<input type="email" ng-model="username" class="lab1" />
</br>
</br>
<label></label>Password:</label>
<input type="password" ng-model="password" class="lab2">
</br>
<button type="submit" ng-click="submit()" class="buttonclass">login</button>
</form>
</body>
</html>

In angular js you can use $location. Inject it in your controller :
app.controller('MainCtrl', function($scope, $location) { ... }
And if you want to redirect to google use its url() method :
$location.url('http://google.fr');
you can also use path() method for relative url :
$location.path('home'); // will redirect you to 'yourDomain.xx/home'
https://docs.angularjs.org/api/ng/service/$location

It is worth noting the current documentation for $location. Specifically the quote:
When should I use $location?
Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.
What does it not do?
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
If you need to redirect the browser to a new page, $window.location is definitely recommended.

Try this,
var homeApp = angular.module('HomeApp', []);
homeApp.controller('HomeController', function ($scope, $http, $window) {
$scope.loginname = "Login To Demo App";
$scope.login = function () {
var name = $scope.username;
var pwd = $scope.password;
var req = {
method: 'POST',
url: '../Account/LoginAccount',
headers: {
'Content-Type': undefined
},
params: { username: name, password: pwd }
}
$http(req).then(function (responce) {
var url = '';
if (responce.data == "True") {
url = '../Account/WelcomePage';
$window.location.href = url;
}
else {
url = '../Account/Login';
$window.location.href = url;
}
}, function (responce) {
});
}
});

You can use $window.location.href in AngularJS
app.controller('MainCtrl', function ($scope,$window) {
$scope.formData = {};
$scope.submitForm = function (formData){
$window.location.href = "jobs";
};
})

Angular has its own location handler named $location which I prefer to use in angular app;
app.controller('MainCtrl', function($scope, $location) {
inject to your controller and use as following;
$location.path('http://foo.bar')

My two cents -
I could not get $window.location.href or $location.path to work to navigate away from a page. In the documentation for $location (under caveats) it says:
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.
$location Caveats
Documentation for $window is... lacking. Regardless, neither of the services worked for me in the controller (though $location.path works in my index.run file).
In this project I am using ui-router, so doing this worked:
$state.go('state.name'); -- where state.name is the string of the state/page name to which the user wants to go, i.e. 'index.users'

Related

how to show pdf file in ionic app with out download

Things i did :
used inappbrowser
used google doc
used webview
so i have tried all these methods to show the pdf file in android device using ionic. But no use, i can see the download button in all these methods. Can any one tell me how can i display pdf without download option for user.
my code :
<div class="col col-50 clsGrid" ng-click="showFile('http://www.orimi.com/pdf-test.pdf')">
</div>
my pdf file :
http://www.orimi.com/pdf-test.pdf
My JS :
$scope.showModal = function(templateUrl) {
$ionicModal.fromTemplateUrl(templateUrl, {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$ionicLoading.show({
duration: 1000
});
$scope.modal = modal;
$scope.modal.show();
});
}
// Close the modal
$scope.closeModal = function() {
$scope.modal.hide();
$scope.modal.remove()
};
$scope.showFile = function(FileUrl) {
var file = FileUrl;
console.log(file);
//var openurl = cordova.InAppBrowser.open(file, '_blank');
// var openurl = cordova.InAppBrowser.open(file,'_blank', 'location=yes');
// var openurl = cordova.InAppBrowser.open("https://docs.google.com/viewer?url=" + file, '_blank');
// var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true', '_blank');
//window.open("https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true",'_blank');
var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true&toolbar=0&navpanes=0&scrollbar=0', '_blank');
}
I tried all ways. But not able to find the solution.If any one know it will be usefull.If any expert in this, i can send my demo project for reference .
Thanks in advance !
You will need to use ng-pdfviewer.
AngularJS PDF viewer directive using pdf.js.
<button ng-click="prevPage()"><</button>
<button ng-click="nextPage()">></button>
<br>
<span>{{currentPage}}/{{totalPages}}</span>
<br>
<pdfviewer src="test.pdf" on-page-load='pageLoaded(page,total)' id="viewer"></pdfviewer>
and in your AngularJS code:
var app = angular.module('testApp', [ 'ngPDFViewer' ]);
app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope, pdf) {
$scope.viewer = pdf.Instance("viewer");
$scope.nextPage = function() {
$scope.viewer.nextPage();
};
$scope.prevPage = function() {
$scope.viewer.prevPage();
};
$scope.pageLoaded = function(curPage, totalPages) {
$scope.currentPage = curPage;
$scope.totalPages = totalPages;
};
}]);

HTTP Error 403.14 - Forbidden when uploading file angularjs

I am creating a web app in which I am storing user images in my folder, after a while I found an example which helps me,
but I am getting the error
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.
and my code is
source
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload-shim.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload.js"></script>
</head>
body
<div ng-app="myApp" ng-controller="myCtrl">
<input type="file" file-model="myFile" />
<button ng-click="uploadFile()">upload me</button>
save
</div>
script
<script>
//inject angular file upload directives and services.
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
})
.error(function () {
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function ($scope, fileUpload) {
$scope.a = function () {
console.log('called');
}
$scope.uploadFile = function () {
console.log('called');
var file = $scope.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "http://localhost:9206//file//";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
and the url is
http://localhost:9206//file//
let me explain this
this is my one page application, I want to save image in my folder called file,
when a user uploaded his/her image, the image should be stored in the folder,
but instead of this I am getting this error
(HTTP Error 403.14 - Forbidden)
what I need to do now?
It appears that the problem can be fixed by enabling the IIS. You can enable and configure the Internet Information Service (IIS) on your computer (given that you are using localhost) by following the instructions on this link:
https://msdn.microsoft.com/en-us/library/ms181052(v=vs.80).aspx

Using Disqus with cordova (Login not working)

I've a problem using disqus in my cordova/angularjs mobile app.
My app needs to open a blog page and shows comments using disqus.
Checking on StackOverfolow, Google and Disqus's website I found this tutorial (https://help.disqus.com/customer/portal/articles/472096) that I followed.
First I created a static page to open comments like this one https://github.com/disqus/DISQUS-API-Recipes/blob/master/mobile/js/mobiletemplate.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
</head>
<body>
<div id="disqus_thread">
</div>
<script type="text/javascript">
var params;
var disqus_url;
var disqus_title;
var disqus_shortname;
var disqus_identifier;
window.onload = function () {
var match,
pattern = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pattern, " ")); },
query = window.location.search.substring(1);
params = {};
while (match = search.exec(query))
params[decode(match[1])] = decode(match[2]);
if (params["shortname"] === undefined || params["url"] === undefined || params["title"] === undefined) {
alert("Required arguments missing");
}
else {
loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
}
};
function loadComments(shortname, url, title, identifier) {
disqus_url = url;
disqus_title = title;
disqus_shortname = shortname;
if (identifier !== undefined)
disqus_identifier = identifier;
else
disqus_identifier = "";
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = false;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
</script>
<noscript>
Please enable JavaScript to view the
<a href="http://disqus.com/?ref_noscript">
comments powered by Disqus.
</a>
</noscript>
<a href="http://disqus.com" class="dsq-brlink">
blog comments powered by
<span class="logo-disqus">
Disqus
</span>
</a>
</body>
</html>
Then I open the page above using Cordova In App Browser (https://github.com/apache/cordova-plugin-inappbrowser) and I handle the login like suggested in the tutorial
$cordovaInAppBrowser.open($scope.dsqUrl, '_blank', options).then(function(event) {
$rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event) {
console.log(event);
if (event.url === 'http://disqus.com/next/login-success/') {
console.log("Login OK");
$cordovaInAppBrowser.open($scope.dsqUrl, '_blank', options).then(function(event) {
// success
}).catch(function(event) {
// error
});
};
});
}).catch(function(event){
//error
});
The result is:
open the comments page
click on login
fill the login form
redirect (automatically) to the comments page
Now I've to be able to comment, but the comments page ask me to login another time....
If I try to login, because the cookies, the page knows that I've already logged in and redirect to comments page
The problem is that the comments page ask me always to login.
If I click on profile button it opens correctly my profile so the login has been done successfully
The same issue if I close the comments page and I reopen it
Do you know how can I fix this issue?
Thank you very much in advance
Michele Riso

Angular service not storing data between two controllers

I am trying to use a service to set title in controller1 and then access title in controller2.
sharedProperties.setTitle(title) works in controller1, but when I try to get the title in controller2, it gets "title" (the initial value) instead of the new value.
I've also tried storing title in an object but it didn't work.
app.service('sharedProperties', function () {
var title = "title"
return {
getTitle: function () {
return title;
},
setTitle: function (val) {
title = val;
}
}
});
app.controller('controller1', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
sharedProperties.setTitle(title);
});
}]);
app.controller('controller2', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$scope.sharedTitle = function() {
return sharedProperties.getTitle();
};
}]);
And in my view, I have {{ sharedTitle() }} which should, as I understand it, update the title text with the new title.
Also, in case this is relevant: the two controllers are linked to two different html pages.
What am I doing wrong?
EDIT
Updated button listener:
$('body').on("click", "button[name=btnListItem]", function () {
// gets the text of the button (title)
var title = $(this).text();
sharedTitle(title);
alert(sharedProperties.getTitle());
document.location.href = '/nextscreen.html';
});
$scope.sharedTitle = function (title) {
sharedProperties.setTitle(title);
};
It seems to be correct in your sample code. I setup jsfiddle and it seems work correctly. Finding out a difference between my jsfiddle and your actual code would help you to find the problem you should solve.
Javascript:
angular.module('testapp', [])
.service('sharedProperties', function(){
var title = 'title';
return {
getTitle: function(){
return title;
},
setTitle: function(val){
title = val;
}
};
})
.controller('controller1', function($scope, sharedProperties){
$scope.change_title = function(newvalue){
sharedProperties.setTitle(newvalue);
};
})
.controller('controller2', function($scope, sharedProperties){
$scope.sharedTitle = function(){
return sharedProperties.getTitle();
};
})
Html:
<div ng-app="testapp">
<div ng-controller="controller1">
<input ng-model="newvalue">
<button ng-click="change_title(newvalue)">Change Title</button>
</div>
<div ng-controller="controller2">
<span>{{sharedTitle()}}</span>
</div>
</div>
My jsfiddle is here.
You have to print console.log(sharedProperties.getTitle()); Dont need return from controller.
So your code of controller2 is $scope.sharedTitle = sharedProperties.getTitle();
You need to use the $apply so that angular can process changes made outside of the angular context (in this case changes made by jQuery).
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
$scope.$apply(function() {
sharedProperties.setTitle(title);
});
});
See plunker
That said, this is BAD PRACTICE because you're going against what angular is meant for. Check “Thinking in AngularJS” if I have a jQuery background?. There are cases when you need to use $apply like when integrating third party plugins but this is not one of those cases.

Can I post a message to facebook wall in my website?

I use the html code in facebook developer but it can't post the message I put in the website
there just appear a windows that you can enter some words
but the
'Facebook for Websites is super-cool' doesn't appear in the window
(just like the website did)
I have applied a appid, is there anything wrong?
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID',
status : true,
cookie : true,
xfbml : true
});
FB.ui({ method: 'feed',
message: 'Facebook for Websites is super-cool'});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
</body>
According to this facebook platform update, since July 12 the message field is no longer supported.
You need to do:
var params = {};
params['message'] = 'Message';
params['name'] = 'Name';
params['description'] = 'Description';
params['link'] = 'http://apps.facebook.com/summer-mourning/';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Caption';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Published to stream - you might want to delete it now!');
}
});
Ref link: http://daipratt.co.uk/using-fb-api-to-make-a-full-post-to-a-users-wall/
Hope it helps
<div id="fb-root"></div>
<script src='http://connect.facebook.net/en_US/all.js'></script>
<p><a onclick='postToFeed(); return false;'>Post to Feed</a></p>
<p id='msg'></p>
<script>
FB.init( {
appId : "YOUR_APP_ID",
status : true,
cookie : true
});
function postToFeed() {
// calling the API ...
var obj = {
method : 'feed',
link : 'https://developers.facebook.com/docs/reference/dialogs/',
picture : 'http://fbrell.com/f8.jpg',
name : 'Facebook Dialogs',
caption : 'Reference Documentation',
description : 'Using Dialogs to interact with users.'
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: "
+ response['post_id'];
}
FB.ui(obj, callback);
}
I suggest you to go through the documentation first...
I would suggest you to use the facebook comment plugin instead. It free and easy to implement.
if the user really like your page, they will write something good to you.
Do check out my website -> www.wootube.woolei.com