Linkedin Api dynamic parameter passing - angularjs

I have a chrome extension and on its content script which runs at local host
"content_scripts": [{
"js": ["lib/jquery.js", "searching_helper.js"],
"matches": [ "http://localhost:8089/*"]
}]
In searching_helper.js I am getting the public profile url of linkedin members from another content script.
chrome.runtime.sendMessage({u:true},function(response) {
console.log(response.ans);
linkedinProfileUrl = response.ans.profileUrl;
console.log('linkedinProfileUrl' + linkedinProfileUrl);
});
In linkedinProfileUrl variable I am getting the public profile url a linkedin profile being viewed.
Now what I want is that I have a server side code in which i have to give its url which is using linkedin api.
Server side code of
index.html file
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
//here goes the api key, and the callback function
api_key: ******
onLoad: onLinkedInLoad
authorize: true
</script>
the function which runs on onload is defined in linkedin.js file
function onLinkedInLoad() {
onLinkedInLogin();
}
//execute on login event
function onLinkedInLogin() {
//pass user info to angular
angular.element(document.getElementById("appBody")).scope().$apply(
function($scope) {
$scope.getLinkedInData();
}
);
}
and this getLinkedInData() method is defined in a controller .
$scope.getLinkedInData = function() {
if(!$scope.hasOwnProperty("userprofile")){
IN.API.Profile("https://in.linkedin.com/in/latika").fields(
[ "id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl","positions","location","email-address"]).
In this IN.API.Profile("https://in.linkedin.com/in/latika") here I want to pass the linkedinProfileUrl got from the content script . and the problem is that if I pass parameters in index.html file it throws error.

I got the answer . I used localStorage to get the url.
In searching_helper.js used
localStorage.setItem('url', linkedinProfileUrl);
And then in linkedin.js used
function onLinkedInLogin() {
var url = localStorage.getItem('url');
//pass user info to angular
angular.element(document.getElementById("appBody")).scope().$apply(
function($scope) {
$scope.getLinkedInData(url);
}
);
}

Related

Google Maps API dynamic load with AngularJS

I'm trying to load Google Maps API using AngularJS:
<html data-ng-app="search-app">
<head data-ng-controller="GoogleMaps">
<script ng-src="{{mapsUrl}}" type="text/javascript"></script>
....
</head>
and controller for that part:
search.controller('GoogleMaps', [
'$scope','$sce',
function GoogleMaps($scope,$sce) {
var mapsUrl = '//maps.google.com/maps/api/js?sensor=false&key=my_api_key';
$scope.mapsUrl = $sce.trustAsResourceUrl(mapsUrl);
}
]);
but when the Google Map API is called within the search controller it throws and error
this.setMap is not a function
for
function CustomMarker(latlng, map, args) {
this.latlng = latlng;
this.args = args;
this.setMap(map);
}
but when I will replace {{mapsUrl}} with full URL in the HTML header it will works.
Any thoughts on that?
I have ended up appending URL to the header as a script on load event
function require(url, callback)
{
var element = document.createElement("script");
element.src = url;
element.type="text/javascript";
element.addEventListener('load', callback);
document.getElementsByTagName("head")[0].appendChild(e);
}

Title: "Angular Js Data is not formatted properly"

When a user clicks through to their User Profile Page they are supposed to see friendly dates. Instead they see the raw Javascript date. I am using a service to transform the data. I think the problem is related to ng-click and href that is being used. I do this throughout my Single Page Appllication using the MEAN Stack and the only pages that have problems are the ones that use ng-click to open.
The link which navigates the user to their User Profile is the following
<a ng-show="authenticated" href="#/usrProfile" ng-click="showUser(current_user)">{{current_user}} </a>
Clicking on the above html link opens their User Profile page. The correct date time is there but it is not rendered properly. It shows, for example "2015-12-01T01:19:22.947Z", instead of "Nov 30, 2015" which is adjusted for their timezone and more human readable. If the user clicks the back button of the browser, then clicks the forward button it will show the same date properly rendered.
The date is rendered by Angular outside the controller using a service. The service renders the date with the following code
vUsrProfile.usrCreatedDate = $filter('date')(vOriginalUsrCreatedDate,"MMM d, y", $rootScope.current_offset);
The data in the service is passed to the controller using the following code
var usrSingle = usrTracker.getProperty();
$scope.usrSingle = usrSingle;
The code to display that date is this code
<h5 title="Date {{usrSingle.username}} joined">{{usrSingle.usrCreatedDate}}</h5>
I am missing something. It feels like the data is being displayed before the service has transformed it.
I hope this makes sense. It seems like a hard problem to describe.
MORE DETAILS:
Controller code. Passing data from one controller to another.
// Controller for link
app.controller('mainController', function ($scope, usrTracker, usrServiceById) {
// removed non-relevant code ...
// get single user data
$scope.showUser = function (vUsername) {
usrTracker.setProperty(usrServiceById.get({ "username": vUsername }));
};
// removed non-relevant code ...
});
// Controller User Profile Page
app.controller('usrPageController', function ($scope, usrTracker) {
var usrSingle = usrTracker.getProperty();
$scope.usrSingle = usrSingle;
// removed non-relevant code ...
});
// factory for a single user
app.factory('usrServiceById', function ($resource) {
return $resource('/api/usrProfile/:id', { id: '#_id' });
});
// factory to hold user data between controllers
app.factory('usrTracker', function ($filter,$q,$rootScope) {
var vUsrProfile = {
username: 'username',
usrEmail: 'usrEmail'
, usrFirst: 'usrFirst'
, usrLast: 'usrLast'
, usrTimezone: 'usrTimezone'
, usrGender: 'usrGender'
, usrBirth: 'usrGender'
, usrPrefHours: 'usrPrefHours'
, usrSocAuth: 'usrSocAuth'
, usrCreatedDate: 'usrCreatedDate'
, usrAccessToken: 'usrAccessToken'
, usrRefreshToken: 'refreshToken'
, usrOffset: '+0000'
, usrDesc: 'usrDesc'
, userSocId: 'userSocId'
};
return {
getProperty: function () {
var vOriginalUsrCreatedDate = vUsrProfile.usrCreatedDate;
vUsrProfile.usrCreatedDate = $filter('date')(vOriginalUsrCreatedDate,"MMM d, y", $rootScope.current_offset);
return vUsrProfile;
},
setProperty: function (value) {
vUsrProfile = value;
}
};
});

Angular controller not updating view without page refresh

I have a problem with my login routine using passport js, express and angular. While the login as such works smoothly I want to use the window object to store the current logged in user for authentication purposes.
After username and password are validated using passport I am using the successRedirect, that triggers index.render
// Set up the 'signin' routes
app.route('/signin')
.post(passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/signin',
failureFlash: true
}));
exports.render = function(req, res) {
// Use the 'response' object to render the 'index' view with a 'title' and a stringified 'user' properties
console.log('Window Object:',req.user);
res.render('index', {
title: 'Test',
user: JSON.stringify(req.user)
});
};
Once I login to the application the window.user object turns from null to the following (index.ejs).
<!-- Render AngularJS views -->
<header data-ng-include="'header.client.view.html'"></header>
<section data-ui-view></section>
<div id="contactform" data-ng-include="'contactform.client.view.html'"></div>
<footer data-ng-include="'footer.client.view.html'"></footer>
<!-- Render the user object -->
<script type="text/javascript">
window.user = {"_id":"55cb06e523d7d6680d14c215","provider":"local","firstName":"Karl","lastName":"Karl","email":"karl.karl#test.com","__v":0,"created":"2015-08-12T08:42:13.807Z","active":true,"fullName":"Karl Karl","id":"55cb06e523d7d6680d14c215"};
</script>
Now I have been very unsuccessful in retrieving the window.user object in my angular controller as it is seen as null as long as I haven't done a page refresh.
<!-- Render the user object -->
<script type="text/javascript">
window.user = null;
</script>
So the question is now, how do I retrieve the window object, as I want to update my angular view accordingly, showing in the header that the user has been logged in?
I think you are meant to use a Angular service to store variables that are to be shared amongst controllers. Sorry, I guess I'm trying to nudge you out of your preferred solution to use the Window object to store state.
Some sample code from a common services module
//var com_serv = angular.module('common.services')
com_serv.service('sharedProperties', function () {
var property = 'Not yet set';
return {
getProperty: function () {
return property;
},
setProperty: function (value) {
property = value;
}
};
});
Related SO questions
how-can-i-pass-variables-between-controllers
how-to-pass-dynamic-data-from-one-module-controller-to-another-module-controller

Call CI Controller from ExtJs

I am creating controller in Code Igniter and make form in ExtJs 4.2.1 now from where i call control and how?
i used url property of form and put controller name there but nothing happen
Update
I think i am not clearing my question actually i want to post data through submit function in which i pass data to php file in my server side i use Code Igniter Rest Api so here i want pass data to specific controller
ExtJs is a javascript framework and is executed on the client side. It has its own MCV system.
It makes no sense to mix up a php controller with a javascript view.
Be sure to read the introduction to MVC in ExtJS.
Also in ExtJS you don't call the controller. On initialisation of the app, all controllers get lloaded. In the controller you define what it has to control, and from then on the magic hhappens: The events defined in the controller are fired whenever needed.
In ExtJS 3.3.1
In login form put the buttons and call function submit_login();
buttons: [{
text: 'Login',
handler: function() {
submit_login();
}
}]
Submit_login() code is, I used Ext.Ajax.request to submit login parameters
You can debug the message with alert(response.responseText):
function submit_login() {var useridx = Ext.getCmp('useridx').getValue();var userpasswordx = Ext.getCmp('userpasswordx').getValue();Ext.Ajax.request({url:'".$url."', method:'POST',
params :{useridx:useridx,userpasswordx:userpasswordx},
success:function(response){
//alert(response.responseText);
//return;
var jsonData = Ext.util.JSON.decode(response.responseText);
var resultMessage = jsonData.Message;
var isLogin = jsonData.isLogin;
if (isLogin)
{
window.location = '';
}
else
{
Ext.Msg.alert('Info',resultMessage);
}
},
failure: function(){
Ext.Msg.alert('Not OK');
}
});
}
variable $url is:
$url = "index.php/apps/login";
You can create Apps controller
and create function login
public function login()
{
$this->load->view('login');
}
Create login.php in view
if ($i==1) {
//session_start();
$this->session->set_userdata('userid',$useridx); echo '{"success" : true, "isLogin": true,"Message" : "User Successfully Login"}';
} else {
echo '{"success" : true, "isLogin": false, "Message" : "Salah User: '.$useridx.' dan Password "}';
}
You also do this in Ext JS 4.2.1 with same code.
This is works for me
Andrex Maulana

Backbone Model not compatible with underscore and ASP.NET MVC Web API Controller?

This is a two stage problem when working with backbone.js and a web api controller.
I have a simple web api controller that returns a JSON string, in fiddler the result looks like this:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
I use the following code to fetch a user from my web api
var user = new Usermodel({ id: "1" });
user.fetch({
success: function (u) {
console.log(u.toJSON());
}
});
now my backbone user object looks like this
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
When I try to bind this backbone model object to my view template that looks like this
<form>
<input type="text" value="<%=Heading%>" />
<input type="submit" value="Save" />
</form>
i get, Heading is undefined but when I use id it binds just fine? It seems like underscore does not like the backbone model object and just want a plain JSON object just like the one I get from my web api?
The second problem with this is that when I save my model with user.save({ Heading: "my new heading }); the payload to my web api is the backbone model which is completely wrong because my api expects a user object like this to be sent to the server:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
and not the backbone model with the real object wrapped inside. Is it possible to solve so that underscore can handle backbone models and tell backbone to only send the payload that my end point expects?
You may be able to solve the problem by following these steps:
In addition to using fiddler to inspect your response, look at the response on the network tab of Chrome Developer Tools. If the response does not look like this, then your web api is not returning a valid json response, the problem is most likely within your web api. You need to get/provide more information about your web api to solve the problem. Verify that the response looks like this:
After verifying that the response from the web api is correct, check out the following jsfiddle I modified:
http://jsfiddle.net/J83aU/23/
Fix your client side code referencing the example I have provided.
Properly instantiate the Backbone objects.
Call the view.render function at the correct step, after the response is received from the server.
Make sure that the main content div is actually rendered before creating a view which depends on it for the 'view.el' property.
Declare the 'view.el' property properly, with a string rather than jQuery object.
Use development Backbone and underscore to enable debugging, an important concept when learning to use open source frameworks such as Backbone.
Use jsfiddle's echo/json api to mock a valid ajax json response, exactly as described in step 1.
The following json example you submitted is not even valid json, if you update your question with valid json example, it would be easier to solve the problem. It is unlikely that Backbone created this non-json structure and more likely that you have submitted it here incorrectly.
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
Finally, try to provide a screenshot of the http headers or something for the problem that is occurring when you call model.save().
Read over the Backbone documentation for model.save() and make sure you are doing everything just as the example provided.
You may be able to workaround Backbone's funky save function by forcing your attributes into POST parameters using ajax options:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var saveView = Backbone.View.extend({
events:{
'click #saveSubmitButton':'submit'
},
submit:function (event) {
event.preventDefault();
var view = this,
attributes = $('#saveForm').serializeObject();
this.model.save(attributes, {
data:attributes,
processData:true,
success:function (model) {
//....
}
});
},
render:function () {
//.......
}
});
The attributes property of your model should be unaltered. Send those to your template call:
var MyModel = Backbone.Model.extend();
var newModel = new MyModel({
"$type": "MvcApplication.Models.Article, MvcApplication",
"Heading":"The heading"
});
var html = _.template(templateVar, newModel.attributes);
In your templateVar, which is your templated markup, you should be able to reference $type and Heading directly.
If you have a look at the jsFiddle through a debugger like Firebug you can see that the way you construct the model's URL is not working out, because the forward slash gets encoded. Can you try to modify your model declaration to this:
var Usermodel = Backbone.Model.extend({
url: function () {
return '/api/page/articles/' + this.get('id');
}
});
var user = new Usermodel({
id: '85'
});
And see if you still get the same JSON. Basically if you don't have a Backbone.sync override you are using built-in retrieval that for one shouldn't produce invalid JSON.

Resources