Passing id to json data in angular js - javascript

I am trying to create a chat application through angular and php.
I have created 2 controllers.
One is for displaying the number of peoples online and other controllers is for sending and recieving messages.
In MainController I can show the person name whom I clicked but in SendMessageController I don't know how to show the same person name.
Please help me, I'm new to angular.
here is working Plunker Link

Use service to share the data between controllers.
Inject the service to both controllers.
app.service('userService', function() {
this.userId = '';
this.setUserId = function(id) {
this.userId = id;
};
this.getUserId = function() {
return this.userId;
};
}
Full example

Related

How to share data among the controllers using $broadcast, $on and $emit?

I am new to AngularJS web development.
STEP 1. During initialization, I get login information from a server with http call. Say, UserName, UserID and some other information.
STEP 2. After successful http call, I would like to populate the loginObj object such as
$scope.loginObj = { UserID = '', UserName = '', SomeData: '' };
$scope.loginObj.UserID = 1000;
$scope.loginObj.UserName = 'John Doe';
$scope.loginObj.SomeData = 'Some other data';
STEP 3. I would like to broadcast $scope.loginObj object information with
$rootScope.broadcast method.
All the examples I have seen used some kind of click button. No Button Click
solution.
STEP 4. In the child controller, I would like to receive the broadcasted
information from the Parent Controller.
How can I receive this information?
STEP 5. Some times I get some extra information at the Child Controller as well.
How can I receive this information from Child controller to the Parent
Controller?
Please provide me a solution or direct me some sites where I can get the example.
Instead of using broadcast, create an angularjs service in which you persist the login info you got from http call and you can inject this service in the controller in which you need login info.
create a service like this :
/*app is your angular module name*/
app.factory('authFactory',['$state',function( $state){
var authFactory = {
currentUser: {},
setCurrentUser: function(userinfo){
authFactory.currentUser = userinfo;
},
getCurrentUser: function(){
return authFactory.currentUser;
}
};
return authFactory;
}
in your login controller, inject authFactory, then once user is logged in, call authFactory.setCurrentUser and pass an object ({login: userlogin, email: useremail}). if you need the logged in user in another page, just inject authFactory in that page and call authFactory.getCurrentUser().

AngularJS how to store client-side only info on a $resource instance

I'm trying to figure out "the right way" to store client-side-only state for an instance of a resource.
Suppose I have an ng-resource, Blerg which has only one data field, "name" and per the docs, I do something like
var blergInstance = new Blerg();
blergInstance.name = "Frankie";
blergInstance.$save();
This results in an http POST to the resource URL with json {name: "Frankie"}. Ok, great.
But I actually need to pass that blergInstance around my client-side application interface for a while, and I want to store some state about that blergInstance to tell the client-side application how to display it or how to interact with it. E.g. I've got a directive that wants to optionally display to the user that "Your blergInstance hasn't been saved yet". Or I've got a button elsewhere that will "Moog this Blerg", and I only want to allow a Blerg to be Mooged once before saving.
My first (admittedly naive) approach would be to do something like
var blergInstance = new Blerg();
blergInstance.name = "Frankie";
blergInstance.saved = false //
blergInstance.hasBeenMooged = false //
// pass the blergInstance around to other services, directives, etc
blergInstance.$save();
But now the http POST looks like {name: "Frankie", saved: false, hasBeenMooged: false}.
So how should I attach "state" to the resource instance that is only relevant to the client-side, and which should not be sent to the server?
Why shouldn't you wrap the resource and state into an simple object and pass around, where resource will have the necessary properties only
var stateful = {};
var blergInstance = new Blerg();
blergInstance.name = "Frankie";
stateful.resource = blergInstance;
stateful.saved = false;
stateful.hasBeenMooged = false;
// pass the blergInstance around to other services, directives, etc
stateful.resource.$save();
Here's an alternative to code-jaff's solution
Warning: coffeescript ahead
Step 1:
Create a service with all your API calls
app.service 'Api', ['$resource', ($resource) ->
{
Blerg: $resource "/api/v1/blerg/:id", {id: "#id"}
....
}
]
Step 2:
Call your Api service and pass in an explicit object
app.controller 'Ctrl', (Api) ->
saveBlerg = {}
saveBlerg.name = Blerg.name
Api.Blerg.save(saveBlerg)

angular callback to application

I am using angularjs & cordova in my app. I am stuck at one point i have an button which is used to authorize a person or user. It sends me to the link where i want to allow the user to access. It is getting access and the url of the link shows that the user is http://(websitename).com/approve but how can i get back the user token into my app so that token can be used for further purpose and second thing how can i send my user from the accessing window back to the app.
HTML code:
<button ng-click="login()">Login</button>
Controller code:
$scope.login = function () {
angular.element(document).ready(function () {
var url = 'https://(website_name).com/1/authorize';
var key = 'My App key';
var callbackURl = 'http://localhost/myApp/';
loginService.login(url,key,callbackURl);
});
factory code:
.factory('loginService', function($http,$window){
return {
login: function(url,key,callbackURl){
var clientURL = url+'?callback_method=postMessage&return_url='+encodeURIComponent(callbackURl)+'&expiration=never&name=myApp&response_type=token&key='+encodeURIComponent(key);
var clientWindow = window.open(clientURL,"_blank");
}
}
})
I want to callback my user along with the token to 'http://localhost/myApp/'
how can it be done or is there any easier way to do such queries??
-thanks in advance.

Multiple service( Controller) in breezejs

This below code for one controller
var serviceName = 'breeze/todos', // route to the Web Api controller
manager = new breeze.EntityManager(serviceName);
But i have many controller. How can i do this?
The same above code can apply for as much Breeze controllers as you want.
File : Todos-datacontext.js
var serviceName = 'breeze/todos', // route to the Web Api controller
var manager = new breeze.EntityManager(serviceName);
File: Accounts-datacontext.js
var serviceName = 'breeze/accounts', // route to the Web Api controller
var manager = new breeze.EntityManager(serviceName);
etc...
Do not use several controllers! Every EntityManager you create, fetches metadata - makes http request to associated controller Metadata method.
Instead create 1 controller and work only with it
You should use different controllers+EntityManagers only if you have different repositories

AngularJS - Broadcasting across controllers

Am trying a scenario where i Login, and, on success, want to store that LoginID and pass it to all other controllers for navigation/user management. Similar to a global variable set up, store once use everywhere concept.
Been using angularjs shared Services technique but its not picking the braodcaster LoginID in other controllers.
High level details:
1) Login HTML calls Login Controller from where i call back end server for user authentication
2) On success, broadcasted LoginID via shared service
3) from Login HTML, page navigates to OrderMenu Html and calls OrderMenu controller where am trying to fetch the User id which was broadcasted via the shared service.
4) but in the Order Menu controller the UserID shown is the initialized value i.e looks like app.factory is being called again and initializing the Broadcasted value.
I want to stop the reloading of app.factory. Looks like am missing something here.Any thoughts would be really helpful here.
Here is a quick implemention example of what you described.
And it seems to be working.
http://plnkr.co/edit/SPAB4W
My service is defined as follows:
app.factory('UserAuth', function() {
return {
userId: 'unknown',
authenticate: function( name ) {
// do server side authentication here...
this.userId = 'authenticatedUserId_Of_' + name;
}
};
});
In this example, when second controller (OrderCtrl) is getting called,
UserAuth.userId does not get re-initialized
and keeps the obtained userId of what authentication gives.
You may want to share your code.

Categories