AngularJS: open default mail application and populate to and subject via link - angularjs

I'm trying to open a link using ng-href and as soon as I click on it, I need it to open an email address and populate its To, Subject and it's Body field. Can this be made possible?
I tried this,
<a ng-click=”sendMail($event)” href=”gmail.com” />
$scope.sendMail = function($event)
{
if($scope.showMailLink == true )
{
$event.preventDefault();
window.location = $event.target.href;
$window.open("mailto:veron#gmail.com?subject=hello&body=fggf_self");
}
};
This is what I've tried and it isn't actually right. Is this a valid approach?

You should use location.href:
location.href = "mailto:veron#gmail.com?subject=hello&body=fggf"
or target the current window:
$window.open("mailto:veron#gmail.com?subject=hello&body=fggf", '_self');
- Example -
View
<div ng-controller="MyCtrl">
<button ng-click="mailWithLocation()">
Mail via location.href
</button>
<button ng-click="mailWithWindowOpen()">
Mail via $window.open()
</button>
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $window) {
$scope.mailWithLocation = function () {
location.href = "mailto:veron#gmail.com?subject=hello&body=fggf"
}
$scope.mailWithWindowOpen = function () {
$window.open("mailto:veron#gmail.com?subject=hello&body=fggf", '_self');
}
});

Related

Confused in Calling function in angularjs using anchortag

i am working on one angularjs project.i have one dropdown in which new email,new contact,new calendar function is there.but these function is working on perticular page only like newmessage function works only on Email page.
i want to call the newMessage function, newAddressbook and new calendar functon from anywhere...
can you help me.
this is my code for that functions.:-
<a ng-href="" ng-click="mailbox.newMessage($event)">Email</a>
Contact
<a href="" ng-click="app.newCalendar()" >Calendar</a>
This should work for you.
In your app.js write following code
app.run(['$rootScope', function($rootScope) {
$rootScope.newMessage = function($event) {
// do something
}
$rootScope.newAddressbook = function($event) {
// do something
}
$rootScope.newCalendar = function($event) {
// do something
}
}]);
In Safari and IE "javascript:void(0)" is treated as unsafe so include following code into your app config
app.config(['$compileProvider',function($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|javascript|chrome-extension):/);
}])
// html code
<a ng-href="javascript:void(0)" ng-click="$root.newMessage($event)">Email</a>
Contact
<a href="javascript:void(0)" ng-click="$root.newCalendar($event)" >Calendar</a>
There may be few details which you might have missed , try embedding controller to the respective div which you are using .
Or you can declare the scope as "root" ('$rootScope') into your model .
Hope this will help .
var app = angular.module('SOGo.Common')
app.controller('navController', navController);
app.run(['$rootScope', function($rootScope) {
$rootScope.newMessage = function($event) {
// do something
}
$rootScope.newAddressbook = function($event) {
// do something
}
$rootScope.newCalendar = function($event) {
// do something
}
}]);
});

AngularJS ng-click doesn't work in digest cycle

Html:
<a href id="link "ng-click="print(arg)"> print </a>
Angularjs controller:
$scope.return_promise =function(arg){
return $http.post('\path');
)};
$scope.print = function(arg){
url ="other/path/"
$scope.return_promise(arg).then(function(r){
if(r){
$('#link').attr('href', url);
});
};
Problem: I checked with chrome debugger, the href actually updated, but the event doesn't trigger (i.e. not go to the url). If I click it again, it works.
If I add a statement document.getElementById('#link').click() at the end of if clause, it will prompt an error "digest cycle is in progress"
How can i solve this.
Not sure if I get your question. First, check if the code you paste is the code you wanted add here, because it has numerous errors. If you would like to replace dynamically href attribute do it like so:
<div ng-controller="SomeCtrl as ctrl">
print
</div>
(function () {
'use strict';
angular
.module('module')
.controller('SomeCtrl', SomeCtrl);
SomeCtrl.$inject = ['$scope'];
function SomeCtrl($scope) {
var vm = this;
vm.url = "#";
vm.return_promise = function (arg) {
return $http.post('/path');
};
vm.print = function (arg) {
var url = "other/path/";
vm.return_promise(arg).then(function (r) {
if (r) {
vm.url = url;
}
});
};
}
}());

How can I duplicate the functionality of a Javascript confirm with an AngularJS service?

I created this alert service:
class AlertService {
msg = null;
constructor() { }
confirm = (msg) => {
var self = this
this.msg = msg;
}
cancel = () => {
this.msg = null;
return false;
}
okay = () => {
this.msg = null;
return true;
}
}
What I would like to do it to have in my controller something like this:
alertService.Confirm("Confirm or cancel")
.then(function () {
ts.doDelete(es.exam.examId)
}
Here's my html. Note that al is already wired to the AlertService.
<div id="alert"
ng-show="al.msg">
<div>{{ al.msg }}</div>
<button ng-click="al.okay()">
Okay
</button>
<button ng-click="al.cancel()">
Cancel
</button>
</div>
My problem with this is I know how to call the confirm() and pass it the message but how can I make the alert service sit waiting until the user presses the Cancel or Okay buttons in a similar way to when I use the javascript confirm to make a confirmation box appear on my screen?
You have to return promise from Confirm method. And resolve it or reject on yes/no handlers.
http://andyshora.com/promises-angularjs-explained-as-cartoon.html
Here you can find similar solutions:
http://www.bennadel.com/blog/2632-creating-asynchronous-alerts-prompts-and-confirms-in-angularjs.htm
https://github.com/likeastore/ngDialog

Refresh a Bootstrap navbar using AngularJS

I am currently developing a new project that uses AngularJS and Twitter Bootstrap 3.0 for styling.
The project also uses ASP.NET MVC WebAPI to provide a RESTful API with role based security as well as generating bearer and refresh tokens using Owin and OAuth.
One of the key aspects of the project is that it must be able to refresh the navbar menu by adding and/or removing menu options depending on the roles/permissions assigned to individual users. If a user is currently logged into the application and a system administrator decides to add or removed roles for the logged in user I would like AngularJS to automatically reload the navbar, which will magically show or hide options based on the roles the user has.
I do not know very much about AngularJS at this point and would like to know if this is possible? I have heard something called $scope.apply() and that it could be used for this, but as an inexperienced AngularJS user I am not sure how this could be used.
This is a portion of my view that displays the menu bar, and as you can see I am using functions to show/hide menu options. I'd like these functions to be re-evaluated again if their values change once a new refresh token has been generated by a WebAPI call.
<li data-ng-if="isAuthenticated()" class="dropdown">
Invoice <b class="caret"></b>
<ul class="dropdown-menu">
<li><a data-ng-if="isUserInInvoiceRole()" data-ui-sref="addInvoice">Add Invoice</a></li>
<li data-ng-if="isUserInInvoiceRole()" class="divider"></li>
<li><a data-ng-if="isUserInCreditNoteRole()" data-ui-sref="addCreditNote">Issue Credit Note</a></li>
<li data-ng-if="isUserInCreditNoteRole()" class="divider"></li>
<li><a data-ui-sref="showDaybook">Daybook</a></li>
<li class="divider"></li>
<li><a data-ui-sref="showCustomerLedger">Customer Ledger</a></li>
</ul>
</li>
At present the only way I can force the navbar to be refreshed is by doing a page refresh via F5, which proves that the role based system works, but I'd like it to work automatically by reloading the navbar.
Controller
'use strict';
appModule.controller('indexController', ['$scope', '$state', 'authService',
function ($scope, $state, authService) {
$scope.isAuthenticated = function () {
return authService.isAuthenticated();
};
$scope.isUserInCreditNoteRole = function () {
return authService.isAuthenticated() && authService.isUserInCreditNoteRole();
};
$scope.isUserInInvoiceRole = function () {
return authService.isAuthenticated() && authService.isUserInInvoiceRole();
};
$scope.isUserInOrderRole = function () {
return authService.isAuthenticated() && authService.isUserInOrderRole();
};
$scope.isUserInAdminRole = function () {
return authService.isAuthenticated() && authService.isInAdminRole();
};
}]);
Auth service
Here is the auth service with the relevant code. Bear in mind that the [roles.xxx] are just constants.
'use strict';
appModule.factory('authService', ['$http', 'roles',
function ($http, roles) {
var authServiceFactory = {};
var authentication = {
isAuth: false,
roles: "Anon"
};
var checkRoles = function (access) {
var result = false;
for (var a in access) {
console.log(access[a]);
for (var b in access[a]) {
if (authentication.roles.indexOf(access[a][b]) >= 0) {
result = true;
break;
}
}
if (result)
break;
}
console.log('result ' + result);
return result;
};
var isUserInInvoiceRole = function () {
return checkRoles([roles.invoice]);
};
var isUserInOrderRole = function () {
return checkRoles([roles.order]);
};
var isUserInCreditNoteRole = function () {
return checkRoles([roles.creditNote]);
};
var isInAdminRole = function () {
return checkRoles([roles.admin]);
};
var isAuthenticated = function () {
return authentication.isAuth;
}
authServiceFactory.isAuthenticated = isAuthenticated;
authServiceFactory.isUserInCreditNoteRole = isUserInCreditNoteRole;
authServiceFactory.isUserInInvoiceRole = isUserInInvoiceRole;
authServiceFactory.isUserInOrderRole = isUserInOrderRole;
authServiceFactory.isInAdminRole = isInAdminRole;
return authServiceFactory;
}]);
I have managed to resolve this myself after understanding how AngularJS watches updates to a controllers' scope.
I simply repopulated the authentication object in the authentication service, after a new refresh token had been retrieved and the nav bar updated instantly.

how to implement google+ sign-in with angularjs

I have an AngularJS app, and I want to implement G+ sign-in. I've gone through their samples, and they work as standalone apps.
https://developers.google.com/+/web/signin/
In my Angular app, I am able to display the G+ sign-in button. But I'm stuck on the callback. Do I put the callback function in my controller js file?
If so, and given this controller:
app.controller('myController', function ($scope) {
function signinCallback(authResult) {
On my data-callback, how do I name it so that it goes to signinCallback inside myController?
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="123456789.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read"
</span>
</span>
The Google+ PhotoHunt sample app demonstrates an AngularJS integration with Google+. The sample is available in Ruby, Java, Python, and C#/.NET for web.
Of note should be the following code in the AngularJS front-end:
Markup to render the button in:
<span id="signin" ng-show="immediateFailed">
<span id="myGsignin"></span>
</span>
JavaScript to glue the markup to code:
$scope.signIn = function(authResult) {
$scope.$apply(function() {
$scope.processAuth(authResult);
});
}
$scope.processAuth = function(authResult) {
$scope.immediateFailed = true;
if ($scope.isSignedIn) {
return 0;
}
if (authResult['access_token']) {
$scope.immediateFailed = false;
// Successfully authorized, create session
PhotoHuntApi.signIn(authResult).then(function(response) {
$scope.signedIn(response.data);
});
} else if (authResult['error']) {
if (authResult['error'] == 'immediate_failed') {
$scope.immediateFailed = true;
} else {
console.log('Error:' + authResult['error']);
}
}
}
$scope.renderSignIn = function() {
gapi.signin.render('myGsignin', {
'callback': $scope.signIn,
'clientid': Conf.clientId,
'requestvisibleactions': Conf.requestvisibleactions,
'scope': Conf.scopes,
'apppackagename': 'your.photohunt.android.package.name',
'theme': 'dark',
'cookiepolicy': Conf.cookiepolicy,
'accesstype': 'offline'
});
}
Within processAuth, you should see an access token and can update your UI to reflect this. You can also see the full controller's JavaScript code on GitHub.
I am not sure if this works, but I would try it like this:
module.factory("GPlusAuthService", function ($q, $window) {
var signIn;
signIn = function () {
var defered = $q.defer();
$window.signinCallback = function (response) {
$window.signinCallback = undefined;
defered.resolve(response);
};
gapi.auth.signIn({
clientid: "123456789.apps.googleusercontent.com"
cookiepolicy: "single_host_origin"
requestvisibleactions: "http://schemas.google.com/AddActivity"
scope: "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read",
callback: "signinCallback"
})
return defered.promise;
};
return {
signIn: signIn;
}
});
module.controller('myController', function ($scope, GPlusAuthService) {
$scope.signIn = function() {
GPlusAuthService.signIn().then(function(response) {
});
}
});
<span id="signinButton" ng-controller="myController">
<span class="g-signin" ng-click="signIn()"></span>
</span>
Function that is going to be called after user agrees to sign in is specified in data-callback, this function needs to be globally accessible, that is bound to window object.
Accessing global object from controller is an anti-pattern, as a middle ground you can use $window provided by Angular, which you can mock in your tests

Resources