Angular js retreiving and displaying data from backend to front end - angularjs

I am working on app where I have 2 subdirectories inside public namely admin and core. admin is for admin users where we need to login and add,Edit,delete posts while in core we have pages which a public user or visitors can see. Now what I want is that I have a CRUD functionality implement in admin. I have controller, routes and services. but what I don't know is that how can I display the data in core views for public users I needs steps to to re-use some of the code from admin and retrieve and display data in core views.
Here is a link to the directory structure: http://take.ms/LdaWk

Imagine the following structure...
app
|- admin
|- api
|- core
The api defines your CRUD functions. For example, in Slim PHP something like
$api = new \Slim\Slim();
// audio/video
$api->get('/av', 'getAVs');
$api->get('/av/:id', 'getAV');
$api->post('/add/av', 'addAV');
$api->put('/update/av/:id', 'updateAV');
$api->delete('/delete/av/:id', 'deleteAV');
// define functions that handle http requests above...
Now in admin, you can call the api in angularjs using $http. For example calling the resource POST /add/av
var admin = angular.module('adminApp', ['ngRoute']);
admin.controller('addAvCtrl', function($scope, $http, MsgService){
MsgService.set('');
// process the form
$scope.submit = function() {
$http.post('../api/add/av', $scope.formData)
.success(function() {
MsgService.set('Success!');
});
};
$scope.message = MsgService.get();
});
In core you can use the same api to display data. For example calling the resource GET /av/:id
var core= angular.module('coreApp', ['ngRoute']);
core.controller('mediaCtrl', function($scope, $http, $routeParams){
$http.get('../api/av/' + $routeParams.id)
.success(function(response) {
$scope.media_detail = response;
});
});
Obviously, this is a rough outline. You would need to fill out the code, but it displays the principle.

You can implement a component base structure, something like:
Components
TestComponent
AddTestComoonent
EditTestComponent
ListTestComponent
That each component has own module and router. and whenever you want you can just inject the module and use it

Related

AngularJS ngRoute - specify data for target page, with data not appearing in URL

I'm using AngularJS and I would like to redirect a user when he clicks a button on /page1 to /page2. I currently use AngularJS routing for this using ngRoute which works all fine. However, in addition to the redirection, I would also like to pass some data from page1 to page2 to pre-populate some of the HTML on page2. I know that in order to pass such data, I can either specify it in the path parameter,e.g.
/page2/<param1>/<param2>
or as a query string parameter, e.g.
/page2?<key1>=<value1>&<key2=value2>
In both ways, I can retrieve the query string or path params in /page2 using $route.current.params
However, I do not want to do either of the above as I do not want to expose my data on the URL to the user. Is there a way in AngularJS that the parameters can be passed to /page2, such that they are "hidden" from the URL?
Thanks
You can use a service to store data that will survive route changes. Services are singletons that persist through the entire life of the app.
app.service("appData", function() {
var myData;
this.set = function(data) {
myData = data;
};
this.get = function() {
return myData;
};
}
In a controller:
app.controller("viewCtrl", function($scope,appData) {
$scope.myData = appData.get();
//
appData.set(newData);
});
For more information, see AngularJS Developer Guide - Creating Services.

Security on multi page angularjs application - no routing

I have several html pages, each with an angular app isolated without routing (the app is not a Single Page Application)
//new anguar app in each page
var app = angular.module('app', ['ui.bootstrap', …
My token is stored into the localstorage so to secure the application i've added in each pages this block of code:
app.run(function ($window, $localStorage) {
…
if (!$localStorage.currentUser)
$window.location.href = 'Login.html';
});
This approch seems to work, but does exist a better way considering that no routing is used in this application?

How to retrieve data Angular Js

The problem here is that i need to somehow get the information of the user when he logs in. So what is happening is that when he register all goes fine he goes to another page and it says "Welcome" + username And it does it correctly! But when i do it with the login page the username becomes undefined. Im preety sure i like somehow need to store my data in a factory but stumbled on how to. Thats what i think but may not be true. Anways...
Here is the plunker: http://plnkr.co/edit/qB3Gkeq5ji1YQyy0kpGH
Thank you so much for your help!
Use FirebaseAuth
in your controller you're using firebase array not Auth. This is an extract of the correct way to auth with firebase.
// define our app and dependencies (remember to include firebase!)
var app = angular.module("sampleApp", ["firebase"]);
// inject $firebaseAuth into our controller
app.controller("SampleCtrl", ["$scope", "$firebaseAuth",
function($scope, $firebaseAuth) {
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
var auth = $firebaseAuth(ref);
}
]);
Here is a link to the Docs with the exact tutorial. I would advise following it all the way through to learn firebase.

How to use API KEY with YouTube in angularjs and list videos in a playlist?

I want to list a bunch of videos from YouTube in my mobile app using angularjs.
Preferrably I'd like to list all videos of a user/channels specific playlist.
I've gotten the API KEY from Google Developer Console but I don't understand how and where to use it. In this documentation they only go over the oauth method. https://developers.google.com/youtube/v3/code_samples/javascript#authorizing_requests
I tried using the example code straight up from that documentation only to get a message saying I have to authenticate first.
I'd really appreciate some help into this.
How do authenticate using the api key and secondly how to make the request to get the videos in a playlist.
ps. I'm a newbie developer and I'm using angularjs and ionic framework for my first learning project. I'm fresh out of Codeschool's courses in css, jquery, javascript, backbone and angular. ds.
Thanks!
1. How to use the API
If you want videos of a channel you need to use the YouTube API V3. Use youtube.search.list
with the parameters :
part=id, snippet
channelId=ID OF THE CHANNEL
order=date
type=video
How to find ID of a YouTube Channel ?
You can find the id of a channel with his channel name with http://mpgn.github.io/YTC-ID/
More information of youtube.search.list right here.
This is a live demo.
2. With Javascript ?
First, you need to creat a project in console.google.developers.
Enable the API YouTube API V3 (set to on).
In credential part, creat a public access key.
Also if it's a public app, you may interest by : How to protect my public API key ?
This is the basic code to get the videos of a channel :
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<script>
function googleApiClientReady() {
var apiKey = 'your api key';
gapi.client.setApiKey(apiKey);
gapi.client.load('youtube', 'v3', function() {
request = gapi.client.youtube.search.list({
part: 'snippet',
channelId: 'UCqhNRDQE_fqBDBwsvmT8cTg',
order: 'date',
type: 'video'
});
request.execute(function(response) {
console.log(response);
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
3. With AngularJS ?
With AngularJS you need to creat a service 'google' for example, and you can use the service in your controllers.
An sample example : https://gist.github.com/jakemmarsh/5809963
You don't need the part with authentification.
Using deferred is important in this case.
Example in the controller
'use strict';
function init() {
window.initGapi(); // Calls the init function defined on the window
}
angular.module('team')
.controller('VideosCtrl', function ($scope, $window, $sce, googleService) {
$window.initGapi = function() {
$scope.$apply($scope.getChannel);
};
$scope.getChannel = function () {
googleService.googleApiClientReady().then(function (data) {
$scope.channel = data;
}, function (error) {
console.log('Failed: ' + error)
});
};
});
Example in the service googleService
.service('googleService', ['$http', '$q', function ($http, $q) {
var deferred = $q.defer();
this.googleApiClientReady = function () {
gapi.client.setApiKey('YOU API KEY');
gapi.client.load('youtube', 'v3', function() {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: 'PLila01eYiSBjOtR8oqXkY0i5c1QS6k2Mu',
maxResults: 8
});
request.execute(function(response) {
deferred.resolve(response.result);
});
});
return deferred.promise;
};
}])
You need to add this line to your index.html
<script src="https://apis.google.com/js/client.js?onload=init"></script>
Hope it's help you !
You have to use Google APIs Client Library so that gapi object will be defined and examples from google will work.
Include this in the bottom of the page:
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
And than define callback which will proceed with authorization and your logic:
googleApiClientReady = function() {
gapi.auth.init(function() {
// Other code following the example
});
}
In general as per Google documentation there are
The application loads the JavaScript client library.
The application references its API key, which authenticates the application with Google services.
If the application needs access to the user's personal information, it opens a session with a Google auth server. The auth server opens a dialog box which prompts the user to authorize the use of personal information.
The application loads the API for the Google service.
The application initializes a request object (also called a service object) that specifies the data to be returned by the API.
The application executes the request and processes the data returned by the API.
Here is a working example of basic google API authorization process

How to retrieve constants for AngularJS from backend

i have some application settings that i want to retrieve from backend, so that they would be available to all of my application controllers via injection. What is the most angular-way to do that?
1) If i only needed settings for one or few controllers i could retrieve them via routing resolve method, but what about global application scope?
2) I could use the .run() method, but since call will be async i have no guaranties that my config will be loaded before i access controllers.
Currently my settings are returned as a json object, and my templates/html files are simply served by web server. So i cannot embed anything into script tags, parse html on the server side or any similar technique.
I would create a service for your settings. Then using the .run() method, called a service that returns your app settings data:
angular
.module('YourApp',[])
.service('Settings',function(){
this.data = {}
})
.run(function(Settings,$http){
$http
.get('/ajax/app/settings')
.success(function(data){
Settings.data = data
})
})
function Controller($scope,Settings){
// use your Settings.data
}
http://docs.angularjs.org/api/angular.Module#methods_run
There is a neat plugin to do the job. https://github.com/philippd/angular-deferred-bootstrap
You need to change bootstrap method
deferredBootstrapper.bootstrap({
element: document.body,
module: 'MyApp',
resolve: {
APP_CONFIG: function ($http) {
return $http.get('/api/demo-config');
}
}
});
angular.module('MyApp', [])
.config(function (APP_CONFIG) {
console.log(APP_CONFIG);
});

Resources