AngularJS and google cloud endpoint: walk through needed - angularjs

I'm new to AngularJS but I really like the way AngularJS works so I want to deployed it as client side for my Google cloud endpoint backend. Then I immediately get two problems:
1, Where to put the myCallback, so it's able to work into the ANgularJs controller?
<script src="https://apis.google.com/js/client.js?onload=myCallback"></script>
2, How I'm able to do the oauth2? and how the controller knows if the user authorized?
gapi.auth.authorize({client_id: myCLIENT_ID,
scope: mySCOPES,.....
Any help is appreciated.

For loading Google Javascript Library with AngularJs, the callback function passed to onLoad of Google Javascript Library is the function that bootstrap AngularJS, like this:
This goes to the final of html file:
<script src="https://apis.google.com/js/client.js?onload=startApp">
Then, in <head> section you bootstrap angular like this:
<script type='text/javascript'>
function startApp() {
var ROOT = 'http://<yourapi>.appspot.com/_ah/api';
gapi.client.load('myapifromgoogleendpoint', 'version1', function() {
angular.bootstrap(document, ["myModule"]);
}, ROOT);
}
</script>
As described by Kenji, you also need to remove ng-app directive from your html.

Regarding the callback - In order to access an Angular controller you need to use an injector (http://docs.angularjs.org/api/AUTO.$injector)
Simply create a global callback function, and then get reference to the controller from it like this:
window.callbackFunction() {
injector = angular.element(document.getElementById('YourController')).injector()
injector.invoke(function ($rootScope, $compile, $document) {
$rootScope.variable = "stuff you want to inject";
})
}
In this example I'm injecting the data to the rootScope, but this will also work for a specific controller scope (just inject $scope instead)
Can't help with the second question as I'm not familiar with gapi, though making auth2 calls from angularjs is quite straight forward.

Here you have details on how to use angularjs with google endpoints:
https://cloud.google.com/developers/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications?hl=es

Related

AngularJS init firing twice

I have the following code for AngularJS. Within is a checkStatus function that invokes a web api to check a status of a user's PC. The problem I'm having is that the checkStatus() function is firing twice and hitting the back-end service twice. I do not understand why.
<script>
(function() {
var pageApp = angular.module('pageApp', ['commandAPI']);
function PageCtrl ($scope, $http, commandAPI) {
$scope.checkStatus();
}
angular
.module('pageApp')
.controller('pageAppCtrl', PageCtrl);
})();
</script>
Well it seems that somehow the properties of the app and the controller were applied to two HTML elements within the page. Not sure how that happened but there it was.

How to bootstrap another angularjs app after the other?

Does anybody have an idea how to create an angularjs app with modules loginApp and mainApp, login will use login.html and mainApp will use index.html?
Below is the scenario I want to achieve.
Run loginApp
Once authenticated, run mainApp
I am currently doing the above scenario since I want my login page to load faster, so instead of using index.html which has lots of <script> included.
Angular app initialization manually.
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
More information Bootstrap Angular App
You can manually bootstrap app. see here [more][1]
Manually Bootstrapping an AngularJS Application
Let's start by defining our application's main module:
var myApplication = angular.module("myApplication", []);
Now, instead of relying on the ng-app attribute, we can call the angular.bootstrap function manually. We need to hand it both the application root and the name of our main module. Here's how you call it as soon as the DOM has finished loading:
angular.element(document).ready(function() {
angular.bootstrap(document, ["myApplication"]);
});
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp
See also
https://groups.google.com/d/msg/angular/lhbrIG5aBX4/4hYnzq2eGZwJ
http://docs.angularjs.org/api/angular.bootstrap

How to call JS function outside from AngularJS app?

I have JS file with simple function on clear JS:
function Alert(){
alert();
}
In another file I have application on Angular JS.
At first connected simple JS file on page and after Angular JS on tags <head>
How I can call Alert() method from controller Angular JS?
Simple JS file:
$(function(){
function leftTimeInit(){
$.each($('.action-loader'), function(index, val) {
initLoader($(this), $(this).data('percentage'));
});
}
});
Angular JS in controller:
leftTimeInit();
I get error:
Uncaught ReferenceError: leftTimeInit is not defined
You shouldn't do DOM manipulations in your controllers. So you should probably rethink how you want to use that function.
Anyway, leftTimeInit is declared in an anonymous function, and only visible there. You can't call it anywhere else. If you want that, you'll have to move it out of $(function(){}) . But as I've said, not recommended.
As for your Alert() example... In Angular you have access to simple JS global functions via $window (of course, they're global and you could access them anyway, but if you use $window you can mock them in tests).
.controller('Ctrl', function ($scope, $window) {
$window.Alert('something');
});

What's the best way to store URLs, or URL domains, in AngularJS app?

My AngularJS app makes calls to an API which is currently hosted at one service, but was previously hosted at a different one, and in the near future is likely to be hosted yet somewhere else.
The URL is regularly changing. For example from
myfirst.heroku.com/app/user/mike/profile
to
mysecond.bluemix.com/app/user/mike/profile
etc.
Instead of changing the URL in every location everytime, I want to just have to change the part before the /app....
In an Angular App what is the best way to do this?
NOTE: Many of the URLs I use throughout the app, are in modules that are added as dependencies to my main app. So Module1 and Module2 both use the URL in their controllers and resources and are then included in MainApp. So a good solution for me needs to be accessible to all dependee apps. Is that possible.
I would like to suggest you that you must use angular constant, Its similar to a service but it creates a constant value which can be inject everywhere in our angular project.
This is how we can create constant
Constant service:
angular.module('AppName')
.constant('REST_END_POINT', 'https://rest.domain.com/');
Usages in controller:
angular.module('AppName')
.controller('CTRL_NAME', ['REST_END_POINT', '$scope', function(REST_END_POINT, $scope){
//your business logic.
]);
$location.host() is the client browser's 'prefix.domain.suffix'
You can inject $location into whatever scope or service.
angular.module('app',[]).run(function($rootScope, $location){
$rootScope.host = $location.host();
})
Plunk: http://plnkr.co/edit/gDgrlwZFyWNKUJgbHHKj?p=preview
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
</head>
<body>
<i>Host:</i>
<h1>{{host}}</h1>
<script>
angular.module('app',[]).run(function($rootScope, $location){
$rootScope.host = $location.host();
});
</script>
</body>
</html>
I do use request interceptor for this
csapp.factory('MyHttpInterceptor', [function () {
var requestInterceptor = function (config) {
var prefix = "http://api.example.com";
if (config.url.indexOf("/api/") !== -1) {
config.url = prefix + config.url;
}
}
}]);
configure this intercept in app.config like
csapp.config(["$httpProvider", function($httpProvider) {
$httpProvider.interceptors.push('MyHttpInterceptor');
});
now all your api requests would be prefixed with api.example.com.

How do I store data in local storage using Angularjs?

Currently I am using a service to perform an action, namely
retrieve data from the server and then store the data on the server itself.
Instead of this, I want to put the data into local storage instead of storing it on the server. How do I do this?
this is a bit of my code that stores and retrieves to local storage. i use broadcast events to save and restore the values in the model.
app.factory('userService', ['$rootScope', function ($rootScope) {
var service = {
model: {
name: '',
email: ''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
}]);
If you use $window.localStorage.setItem(key,value) to store,$window.localStorage.getItem(key) to retrieve and $window.localStorage.removeItem(key) to remove, then you can access the values in any page.
You have to pass the $window service to the controller. Though in JavaScript, window object is available globally.
By using $window.localStorage.xxXX() the user has control over the localStorage value. The size of the data depends upon the browser. If you only use $localStorage then value remains as long as you use window.location.href to navigate to other page and if you use to navigate to other page then your $localStorage value is lost in the next page.
For local storage there is a module for that look at below url:
https://github.com/grevory/angular-local-storage
and other link for HTML5 local storage and angularJs
http://www.amitavroy.com/justread/content/articles/html5-local-storage-with-angular-js/
Use ngStorage For All Your AngularJS Local Storage Needs. Please note that this is NOT a native part of the Angular JS framework.
ngStorage contains two services, $localStorage and $sessionStorage
angular.module('app', [
'ngStorage'
]).controller('Ctrl', function(
$scope,
$localStorage,
$sessionStorage
){});
Check the Demo
There is one more alternative module which has more activity than ngStorage
angular-local-storage:
https://github.com/grevory/angular-local-storage
You can use localStorage for the purpose.
Steps:
add ngStorage.min.js in your file
add ngStorage dependency in your module
add $localStorage module in your controller
use $localStorage.key = value
I authored (yet another) angular html5 storage service. I wanted to keep the automatic updates made possible by ngStorage, but make digest cycles more predictable/intuitive (at least for me), add events to handle when state reloads are required, and also add sharing session storage between tabs. I modelled the API after $resource and called it angular-stored-object. It can be used as follows:
angular
.module('auth', ['yaacovCR.storedObject']);
angular
.module('auth')
.factory('session', session);
function session(ycr$StoredObject) {
return new ycr$StoredObject('session');
}
API is here.
Repo is here.
Hope it helps somebody!
Follow the steps to store data in Angular - local storage:
Add 'ngStorage.js' in your folder.
Inject 'ngStorage' in your angular.module
eg: angular.module("app", [ 'ngStorage']);
Add $localStorage in your app.controller function
4.You can use $localStorage inside your controller
Eg: $localstorage.login= true;
The above will store the localstorage in your browser application
Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.
One should use a third party script for this called called ngStorage here is a example how to use.It updates localstorage with change in scope/view.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<!-- CDN Link -->
<!--https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js-->
<script src="angular.min.js"></script>
<script src="ngStorage.min.js"></script>
<script>
var app = angular.module('app', ['ngStorage']);
app.factory("myfactory", function() {
return {
data: ["ram", "shyam"]
};
})
app.controller('Ctrl', function($scope, $localStorage, $sessionStorage, myfactory) {
$scope.abcd = $localStorage; //Pass $localStorage (or $sessionStorage) by reference to a hook under $scope
// Delete from Local Storage
//delete $scope.abcd.counter;
// delete $localStorage.counter;
// $localStorage.$reset(); // clear the localstorage
/* $localStorage.$reset({
counter: 42 // reset with default value
});*/
// $scope.abcd.mydata=myfactory.data;
});
</script>
</head>
<body ng-app="app" ng-controller="Ctrl">
<button ng-click="abcd.counter = abcd.counter + 1">{{abcd.counter}}</button>
</body>
</html>

Resources