How to connect and put in JSON instead of mongolab in AngularJS? - javascript

I want to use JSON instead of MongoLab example shown on AngularJS website.
Here's the code from the website:
angular.module('mongolab', ['ngResource']).
factory('Project', function($resource) {
var Project = $resource('https://api.mongolab.com/api/1/databases' +
'/angularjs/collections/projects/:id',
{ apiKey: '4f847ad3e4b08a2eed5f3b54' }, {
update: { method: 'PUT' }
}
);
Is there any way I could connect and put into JSON file available on my folder instead of hosting it to MongoLab?
Any response would be really appreciated!

You can look at this example:
Reading in JSON through Angular Resources Service
You want to return the Project variable from your factory
var Project = $resource('test.json', {} );
return Project;
then use it in the controller after you inject it:
Project.get(function(data){
$scope.bar = data.foo;
});
Update:
After looking thru the 1.1.3 angular-resource.js code, it looks like it always does an http request to get its data. Set up a simple RoR app with a REST interface for testing.
Or use plunker (like the linked question above) for complete remote testing.

Related

Django/AngularJS: How do I access my Python Context Items from my AngularJS Script

Good day SO! I am a beginner thats trying out a Django Project while using AngularJS for my frontend Firebase chat system. Here is a previous question that I asked regarding this project: Firebase/Angular: Messages not showing in HTML, but contain the message objects
I know that it is not wise to use json variables on your html directly while using django/python, but it just so happens that my firebase chat module is using angularJS (and I do not know how to code this chat function in django..), and my angularJS code requires access to my Django's context querysets from View.py.
Is there any way that I can either:
Push json items into my HTML/Template the same way I push context
information into my HTML/Template from Views.py and use it in my
AngularJS Script?
Access my Django/Python's data sets from Context from Views.py?
Here is my AngularJS code for firebase:
var app = angular.module('chatApp', ['firebase']);
app.controller('ChatController', function($scope, $firebaseArray) {
//I want to populate the crisis and sender variables with something from my context
//from Views.py.. Inside planList
var crisis = "Crisis1";
var sender = "Sender1";
//Query
var ref = firebase.database().ref().child(crisis).child('CMO-PMO');
$scope.messages = $firebaseArray(ref);
$scope.send = function() {
$scope.messages.$add({
sender: sender,
message: $scope.messageText,
date: Date.now()
})
}
})
And here is my Views.py Code:
def home(request):
template = loader.get_template('app/home.html')
planList = Plan.objects.filter(plan_crisisID__crisis_status='Ongoing')
context = {
'planList': planList
}
return HttpResponse(template.render(context, request))
Both variables needed in my AngularJS code (crisis and sender) are from the planList context.
Is there any way for me to achieve this? Please give me some assistance.. Thank you so much and I greatly appreciate it :) I will gladly provide any additional information if needed, and will reply promptly too!
I think it's better to use an API for it. You can create an API using DRF very easily. For example:
# Serializer
class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = Plan
fields = ('model_fields',)
# Views:
from rest_framework import generics
Class SomeView(generics.ListView):
queryset = Plan.objects.all()
serializer_class = SomeSerializer
# urls
url(r'^plans$', SomeView.as_view()),
In Angular JS, if you use angular-resource, you can simply get the data by:
res = $resource('/plans')
res.query().$promise.then(function(data) {
console.log(data)}, // You get your data in here
function(error) {
console.log(error)}
)

How to call a file in controller

I have a file in which ii declared my videouploadfolder url and i want to call that file in my js
my config.js
var filepath = {
uploadVideoUrl : './public/videos'
}
I called it in my node.js as
var config = require(config);
config.uploadVideoUrl;
But i am not sure how to call in js,can anyone suggest help please.Thanks.
With angularjs you can make use of constant,
var app = angular.module('configuration', [])
.constant('uploadVideoUrl', './public/videos')
Then you can use in your controller as,
app.controller('Ctrl1', ['$scope','uploadVideoUrl'
function ($scope,'uploadVideoUrl') {
var config = uploadVideoUrl;
}
]);
If you want your config.js file to stay only in server where you have ther services editing it, then you would have to write a REST route in nodeJs to fetch the content of the config and send it back to angularJS client.
If you dont mind saving that config json in your client side itself instead of your server then follow what Sajeetharan has said.

Using meteor and blaze how to convert template to string for an email body?

And how can I set the value of this now? Ie in js? All i see is how to do in handlebars.
From Meteorpedia :
http://www.meteorpedia.com/read/Blaze_Notes
Take a look at "How to render a template to HTML with data"
var toHTMLWithData = function (kind, data) {
return UI.toHTML(kind.extend({data: function () { return data; }}));
};
Use it like this :
var myTemplateAsString=toHTMLWithData(Template.myTemplate,dataContext);
Which is equivalent to previous Spark code :
var myTemplateAsString=Template.myTemplate(dataContext);
Currently Meteor does not natively support server side rendering of templates, and since you are sending emails from the server this creates an issue. Server side rendering is on the Meteor roadmap, but for now we can use a package. its called "Handlebars-server" and it can be found here: https://atmospherejs.com/package/handlebars-server
With Handlebars-server you can compile handlebars templates into strings for use in emails. The package's readme should get you started and show you how to set data context.

AngularJS: Unexpected ngResource get() behaviour

I am trying to fire a simple GET request from my angular app via $resource service (so there is no need to say that I am new to Angular). Since my server side behaves in RESTfull manner, I am trying to use the nice Angular ngResource. Before trying to generate the GET request from my Angular app, I tested the availability of the resource and it returns the expected information when requested.
My service:
services.factory('ScreenInitializer', ['$resource', function($resource) {
return $resource('/angular/screenInitializer/:initializerParameter',
{initializerParameter : '#sectionName'});
}]);
My controller:
app.controller('HomePageController', ['$scope', 'ScreenInitializer', function($scope, ScreenInitializer) {
$scope.searchByOptions = ScreenInitializer.get({sectionName: "homePageSearchBy"});
// Some irrelevant stuff here...
}
My expectation:
According to the book I read and some examples in the net, what I expected is the parameter initilizeParam in the resource URL to be replaced with the argument that I pass to the .get() method and as a result to have a GET request at
localhost:8080/angular/screenInitilizer/homePageSearchBy
What actually happened:
is a GET request where the "homePageSearchBy" is passed as parameter - localhost:8080/angular/screenInitializer?sectionName=homePageSearchBy. Due to that the server responds with 404 - Resource not found. (which is expected since its location is at .../screenInitializer/homePageSearchBy)
My question:
Is my expectation wrong, or I am using ngResource in a bad way?.
Thanks!
From the docs:
If the parameter value is prefixed with # then the value of that parameter is extracted from the data object (useful for non-GET operations).
So this
{initializerParameter : '#sectionName'}
Is irrelevant for GET operations. And this
{sectionName: "homePageSearchBy"}
appends a sectionName parameter because the URL template does not contain sectionName. What you need is
ScreenInitializer.get({initializerParameter : "homePageSearchBy"})
I prefer to new it up, but if you pass an empty object to the get it will work. See below.
$scope.screen = new ScreenInitialize({sectionName: "homePageSearchBy"});
$scope.screen.$get(function(result){ .. do something ..}, function(error){ .. do something ..})
$scope.searchByOptions = ScreenInitializer.get({}, {sectionName: "homePageSearchBy"});
Example plunkr showing the urls (you have to inspect):
http://embed.plnkr.co/kQsMujk9IgGxdxSE2g0E/
Code:
var Screen = $resource(
'/angular/screenInitializer/:initializerParameter',
{initializerParameter : '#sectionName'});
$scope.screen = Screen.get({}, {sectionName: "homePageSearchBy"});
The url this calls:
http://run.plnkr.co/angular/screenInitializer/homePageSearchBy

AngularJS POSTs empty requests?

I'm a newbie in AngularJS and I've faced an issue when I try to make a POST request with AngularJS and it POSTs no parameters with it. I use Sinatra as a RESTful interface.
That's how my Sinatra backend looks:
post '/layer/:layer_id' do
#layer = PageLayer.where(id: params[:layer_id]).first
#layer.content = params[:content]
#layer.save
end
If try to POST with Postman chrome extension - it works! Sinatra saves the content properly. So I'm sure that the backend works as it should.
That's how my angular test code looks:
TestCtrl = ($scope, $routeParams, $http, $resource) ->
$scope.layer = []
Layer = $resource('/layer/:id', {id:'#id'})
$scope.layer = Layer.get {id: $routeParams.layerId}, ->
console.log "Got you!"
$scope.saveContent = ->
$scope.layer.$save()
console.log "Saved!"
angular.module('appDirectives', []).directive "test", ->
return (scope, element, attrs) ->
element.bind "blur", ->
console.log("blur!")
scope.saveContent()
And HTML-code:
<div>Content: {{layer.content}}</div>
<div>
<form>
<input type="text" test ng-model="layer.content">
</form>
</div>
So, the only question is: What's wrong? Why I can make correct request with Postman but not with angularJS? Angular returns empty "content" so Sinatra saves it as "" every time.
I've also attached a structure of a layer:
g {id: 27245, page_id: 2302, external_id: 26518, original_upload: null…}
content: "dfgdfg"
external_id: 26518
id: 27245
layerNumber: 8
page_id: 2302
How can I log what exactly angular POSTs?
Hey this is the exact problem I was having, and the answer now seems so obvious. I knew Angular was sending json, but no matter what I tried it wasn't working. This led me in the right direction, but as for parsing json I had to write
ng_params = JSON.parse(request.body.read)
I had to change 'string' to 'read'. Maybe I have a newer version of the json gem or something. My full save process is like this:
post '/api/v1/test' do
ng_params = JSON.parse(request.body.read)
#foo = Foo.new(ng_params)
if #foo.save
puts "Page Saved"
content_type :json
rabl :foos, format: "json"
end
end
I use rabl to format the json to have control over what json data Sinatra sends back (no emails or passwords please)
My Angular code is just this (have not yet implemented put, patch or delete, nor auto update of data just yet. You still have to refresh the page to see the new post.) And to be clear, I have a table named 'foos', where the ActiveRecord model is 'Foo', and one column named 'anything' (other than timestamps and id, which I make sure are always there).
// app declaration
var app = angular.module("App", ['ngResource']);
// data service
app.factory('Foo', ['$resource', function($resource) {
return $resource('/api/v1/test/:id', {id: '#id'});
}]);
// the controller
app.controller('Controller', function($scope, Foo) {
$scope.foos = Foo.query();
$scope.create = function(anything) {
Foo.save({anything: anything}, function(foo){
$scope.foos.push(foo);
});
};
});
Then in my markup the form looks like this, where the important thing is the call to 'create' with 'anything' as the argument in 'ng-submit'. If you have more than one column in your table you call 'create' with more than one argument ex. 'create(anything, bar)'.
<h3>Add something new</h3>
<form ng-submit="create(anything)">
<input ng-model="anything" type="text">
<button type="submit">Do it</button>
</form>
While displaying the data is
<li ng-repeat="foo in foos">
<p>{{foo.anything}}</p>
</li>
This link solved the problem. Just add
gem 'rack-parser'
to your Gemfile and add this code to config.ru. Will work like a charm.
require 'rack/parser'
use Rack::Parser, content_types: {
'application/json' => Proc.new {|body| JSON.parse body }
}
All right, I've solved the issue. Somehow Sinatra was not properly getting POSTs from Angular and was not automatically putting them into params.
So if we parse the request manually - it works. Like that:
post '/layer/:layer_id' do
#updated_layer = JSON.parse(request.body.string)
#layer = PageLayer.where(id: params[:layer_id]).first
#layer.content = #updated_layer['content']
#layer.save
end

Categories

Resources