PapaParse with Angular JS - javascript

Liked the nice CSV parser & unparser of PapaParse. Can any one help me to get this combine with Angular JS.
I like to make PapaParse work in Angular Way. Trying for a solution.

I actually didn't do anything fancy to load it. Just add it to html file and to my lib folder. In my case: /lib/papaparse.min.js
and to index.html. As usual script:
<script src="lib/papaparse.min.js"></script>
then I just used it in my Controller:
Papa.parse(data, {
complete: function(results) {
console.log("Finished:", results.data);
}
});

You can use value to provide self contained third party libraries.
angular.module('your.app')
.value('yourLib', yourLib);
Then in your controller, or service, you would bring it in the normal way using DI
angular.module('your.app')
.controller('YourController', YourController);
YourController.$inject = ['yourLib'];
function YourController(yourLib) {
//. . .
}
If the third party line is a constructor function, requires it be newed, you may want to create a factory or a provider that has a method that accepts the passes params to the constructor returns a new instance.
Edit
After looking at PapaParse, you would want to register it with the angular injector using value.

just use a front-end modularization tool like requirejs to load papaParser in the context and call the api in any of your controller or service.

Just inject the script url in your index.html & then in your controller, access it as - var Papa = window.Papa;. That's it! You are ready for further actions!

Related

Runtime value in forRoot of Angular Module

In my angular app there is this module called Ngx-Stripe
I have defined it as documentation like following:
NgxStripeModule.forRoot('***your-stripe-publishable key***');
But the problem is I don't get this key on app bootstrap, I am not supposed to hardcode it in angular app.module or global like in index.html when I am using stripe withput any angular library.
I am getting this key on the api call after user proceeds to payment page. How can I define this key in this scenario ?
I wish it'd be straightforward, but the only way I was able to achieve it was something like:
index.html (alternatively webpack-injected script), has to be placed before Angular's sources:
<script>
var STRIPE_KEY = 'paste it here';
</script>
app.module.ts:
declare var STRIPE_KEY;
// ...
NgxStripeModule.forRoot(STRIPE_KEY);
The problem here is .forRoot() has to be statically-analyzed by Angular AoT compiler, so it can't accept what you want it to accept... How about setting the key after you got it via StripeService.changeKey(key: string) method?
Simply import StripeService from ngx-stripe and call changeKey on that service once you have your key.
For lazy loading your Stripe config key you can create your own instance of StripeService using StripeFactory that is available from ngx-stripe.
Check the documentation here for a full explanation:
https://richnologies.gitbook.io/ngx-stripe/core-concepts/service-factory

how to get json data from a angular service using jquery

I am setting data from a angular controller to a service. I need to somehow get this data using jquery or javascript.Is this possible since I am not requesting it from a url?
Angular service
getSeriesData: function () {
return this.legendSeries;
},
setSeriesData: function (legendSeries) {
this.legendSeries = legendSeries;
},
Not sure why you would want to do that (if you explain the scenario better it might help), but in case you want to share data between an angular application and other JS code (e.g. JSON), one way you could go about is to dispatch a global event from the angular service [for example $(window).trigger('myEvent', myJSON] and then catch this on your separate JS code [window.addEventListener('myEvent'...]
Seems like possible using injector
var injector = angular.element('body').injector()
$injector.invoke(function (serviceName) {
var legendSeries = service.legendSeries;
service.setSeriesData(legendSeries);
});

Communication between ViewModels in KnockoutJS

I'm trying to implement communication between my view models in a knockoutjs driven application. I scaffolded it using yeoman tool, and as you can see it uses AMD:
define(['knockout', 'signals', 'text!./nav-bar.html'], function(ko, Signal, template) {
function NavBarViewModel(params) {
this.route = params.route;
}
return { viewModel: NavBarViewModel, template: template };
});
I have to define an object that I would later use to dispatch events, right? Something like that:
var EventDispatcher = {
itemClicked: new Signal()
};
And then, whenever something happens in the NavBarViewModel I'd like to do:
EventDispatcher.itemClicked.dispatch();
The problem is - where should I put this EventDispatcher thing? It's obvious that it should be some kind of a global object, so that every VM could get a hold on it, but it would be ugly. Dependency injection came to mind, since everything else in this architecture I choose is done this way, but how to achieve that? I come from WPF, MVVM world, and so far I've used MVVMLight framework which had this great Messenger component. Is there anything like that in the JS world (and if it's js-signals lib I'm already using, then how should I use it to achieve my goal?)
I could also use the subscribable object built into the knockout fw, but the question still stands - where to put it (or how to share the instance between VMs)?
You'd quite simply inject it by including it in your define.
First, create a new file, EventDispatcher.js with your EventDispatcher code inside (and other relevant Knockout bits, like returning the view model and whatnot).
Then in your current file add it in:
define([ ... , ... , "EventDispatcher"], function( ... , ... , EventDispatcher )
Now you can simply call its methods within this file by using:
EventDispatcher.itemClicked.dispatch()
(Where EventDispatcher is what we've named it in our define parameters).
Do bear in mind though that your EventDispatcher.js file will also need the signals file passed to it through its own define wrapper.

Play 2.x: How to use two jsRoutes files in one scala template

I'm using jsRoutes in my Play 2.1.x app. Part of my routes file looks the following way:
GET /assets/template/js/routes/admin.js controllers.Admin.jsRoutes
GET /assets/template/js/routes/salonManagement.js controllers.SalonManagement.jsRoutes
And I would like to use both references in my scala template (that is by design, one controller contains necessary api functions, the other one necessary form submission urls).
So in my scala template I have the following part:
<script type="text/javascript" src="#routes.Admin.jsRoutes()"></script>
<script type="text/javascript" src="#routes.SalonManagement.jsRoutes()"></script>
Unfortunately, each generated javascript file starts with var jsRoutes = {};. Therefore, #routes.SalonManagement.jsRoutes() overrides properties of #routes.Admin.jsRoutes() and I can use only the last jsRoutes object.
Now, I know only one workaround. After each jsRoutes declaration I can insert a script that copies old jsRoutes object to a temporary object and then extends new jsRoutes with itself. But that doesn't look like the right way to go.
Isn't there any better way?
There's nothing special about the "jsRoutes" name. You can keep the same method name for consistency among the various controllers, but just pass a different name to the Routes.javascriptRouter method.
Put this in your template. I put it in a main template that wraps the other pages.
<script src="#controllers.routes.Application.jsRoutes()" type="text/javascript"></script>
and put this in your routes file
#jsroutes for ajax calls
GET /assets/js/routes controllers.Application.jsRoutes()
And then in your Application controller, refer to whatever method in whatever controller you want by implementing this method
public Result jsRoutes()
{
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter("jsRoutes",
routes.javascript.Signup.forgotPassword(),
routes.javascript.Customers.findByName(),
routes.javascript.Customers.findByNumber()
));
}
These correspond with routes like
GET /customerfind/:name controllers.Customers.findByName(name: String)
Note there is no need to include parameters for the calls configured in the jsroutes method. Keeping all of this in one place, the Application controller, seems reasonable as long as it refers to methods implemented in their appropriate controller. Like in this example, a find on customer is in the Customers controller. Also, is kindof nice just having to check the one controller (Application) to see all the methods available through javascript routes for ajax calls.

Accessing Get variable in Angular function

I'm building an app in node express and angular js. I pass a variable to my view, as follows...
app.get('/profile', ensureAuthenticated, function(req, res){
res.render('profile', { user: req.user });
});
I can access the variable in my view like this (jade)...
h1 #{user}
But how can I access this variable from an angular function in a controller or directive?
I wrote a blog post about this topic - How to pass JavaScript Variables from a server to Angular.
In summary, you've got three options:
Use inline JavaScript tags (not recommended)
Make an HTTTP request (as you've shown in your own solution)
Use ngInit
You can read about the details in my post and I'll only show the last, and in my opinion smartest, solution.
To pass your user object from your express server to an Angular controller use the ngInit directive:
div(ng-controller="UserCtrl", ng-init="user= #{JSON.stringify(user)}")
That loads the content into Angular scope and you should be able to access it inside your controller by calling $scope.user.
function UserCtrl($scope) {
console.log($scope.user);
}
ng-init is not the way to load/store constants in Angular. Introducing, the Angular way:
<script>
angular.module('$preloaded', []).constant('$preloaded', <%= preloaded %>)
</script>
You can then inject the $preloaded dependency wherever in your code and access the constants.
It sounds to me like you may be mixing things in a not-ideal way. I think the best way to do this is using $resource in the Angular code to call /profile and get the data that way.
Think of it this way, you just used node to create a webservice, now you use AngularJS to call the webservice from your Services layer. The code for calling it is fairly straight-forward and can be found on the documentation I linked.
You may also want to check out the FoodMe demo, this uses node.js as the webservice layer and angularJS as the client-side UI layer in exactly the way you're setting it up.
Thanks James, the FoodMe demo looks like a great learning resource. Having read your reply, it shifted my thinking enough for me to come up with my own solution. I will add it as an alternative answer, simply because code in comments suck. For the sake of improving my understanding of how node and angular can work together, perhaps you or somebody else might be kind enough to comment on how our two solutions compare, and why or when one might be preferable.
In my express app.js...
app.get('/api/user', api.user);
and in my routes/api.js...
exports.user = function (req, res) {
res.json(req.user);
};
and then in my angular controller...
function profileCtrl($scope, $http) {
$http.get('/api/user/').success(function(data) {
$scope.user = data;
});
}
This is an old post but a relevant one. Zemrico's answers is good but needs to be updated as there are some changes to the jade/pug syntax. Firstly, the link in his answer is broken and should be
http://www.mircozeiss.com/how-to-pass-javascript-variables-from-a-server-to-angular
If you are reading the blog post, please note that the following no longer works as pug no longer accept interpolation as an attribute.
div(ng-controller="UserCtrl", ng-init="user= #{JSON.stringify(user)}")
Instead, please use this.
div(ng-controller="UserCtrl", ng-init="user=" + JSON.stringify(user) )

Categories