AngularJS - access elements in scope - json

I have done a service that gets a json file from the server with the translated values of the labels of my webapp. Seems to work fine:
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function($scope) {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$scope.translation = data;
});
};
});
What I am trying to do is acces that "$scope.translation" from my controler, I tried all and nothing worked. The object is saved in my $scope as you can see:
how can I get the values of the "registroBtnRegistro", "registroErrorRegistro" etc ?
Thanks in advance !
I tried:
console.log($scope.translation); -> undefined
console.log($scope['translation']); -> undefined
console.log($scope.translation.registroBtnRegistro); -> TypeError:
Cannot read property 'registroBtnRegistro' of undefined
console.log($scope.translation['registroBtnRegistro']); -> TypeError:
Cannot read property 'registroBtnRegistro' of undefined

Maybe you're trying to access these values from another $scope that not inherits the scope where you've created your translation model.
Try to assign this model directly to $rootScope, so you can access it from every scope:
mobilityApp.service('serveiTraduccions', function($resource, $rootScope) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$rootScope.translation = data;
});
};
});

this answer is a blind attempt because your original post lacks basic information like the call from the controller.
we can refine it until we make it work.
First, you should be returning something from your method:
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
return $resource(languageFilePath);
};
});
You are using $resource but you might as well use basic $http.get(). at least it doesn't look like a restful api to me.
In any case, because it's an asynchronous request, it will not return the list of translated strings, but a resource "class" that allows methods like get, delete or the more general query():
from the docs: default methods are
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
sidenote: injecting $scope in a service doesn't make much sense to me: services are used to encapsulate common logic accross components. However, you can pass a scope instance as a parameter.
Then, the controller that uses this should have the service injected and use a callback to get the results when they have arrived (asynchronous operation!):
TraduccioCtrl ... {
$scope.translation = {}; // avoid undefined when the view just loads
ServeiTraduccions.getTranslation.query(function (response) {
$scope.translation = response; // and angular's two-way data binding will probably do the rest
});
}
The Angular docs about ng-resource have a working example. Other questions in SO have addressed this already too, like Using AngularJS $resource to get data

Related

Customize Loopback response after save

I have a loopback 2.x app, in which I have a model Conversation and a model Message, with a relationship "Conversation has many messages". I want to customize the response for POST conversations/:id/messages with a json response different than the default, say {status: 'success'}. I tried to use remote hook for the method __create__messages, but it did not work:
Conversation.afterRemote('__create__messages', function(ctx, next) {
ctx.result.data = {
success: 'yes'
};
next();
});
This still returns the default response. How can I return a custom json for a remote method? I have seen examples only for all models, or for all methods: multiple models, multiple methods
Maybe you can try a version of following code below. Also, I think you are meaning to to manipulate data before the method finishes, not after. If you wait, the response will already be created, preventing your intended goal. Let me know if this works (replace with methods that will work for your use case).
Conversation.observe('before save', function(context, next) {
var instance = context.instance || context.data;
if (!instance) return next();
// Your code here
next();
});

Collecting a value from JSON file with ember.js

I am trying to pass a simple variable value into an HTML file using ember.js. My value is contained within a json file called value.json.
My HTML code is as follows:
<h1>I won {{App.moneyvalue}} today!</h1>
However when I pass the json call via ember, it think that the entire call is a variable:
App = Ember.Application.create({
moneyvalue: function () {
return $.getJSON( "js/value.json", function( data ) {
return data.tot;
});
}
}
And returns the following:
I won function () { return $.getJSON( "js/donors.json", function( data ) { return data.tot; }); } today!
As it seems to think that moneyvalue is a string variable as opposed to a value?
The jSON file is superbasic
{
"tot": 100
}
Where is this going wrong?
you're supplying Handlebars with a function, generally you would use a computed or normal property on the object. In this case you really just shouldn't define it in the application scope either, I'd recommend using an application route (it's the root route of your app).
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return $.getJSON( "js/value.json");
}
});
Then in your handlebars just use
<h1>I won {{tot}} today!</h1>
Here's an example: http://emberjs.jsbin.com/OxIDiVU/576/edit

Angular.js reading External JSON Address

Hey guys I am trying to use an EPA API that provides daily UV Index information in JSON.
The link I am trying to read at the moment is:
http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=callBackFn
If you open that link it shows valid JSON, but when I use it in my Angular.js code it does not read it, and my variable stays as unknown. My code is:
var tanApp = angular.module('tanApp')
.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.data = 'unknown';
$http.get('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=callBackFn').success(function(data){
$scope.data = data;
});
tanApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
My HTML code is {{data}}.
When I take out the "JSON" portion, it comes up as XML, since it is the default, and that is actually showing up, but I need it as JSON.
Can someone possibly get this to work or provide some help? I can offer bitcoin as a bounty.
Thanks!
The problem is that the URI you're using returns raw JSON instead of JSONP. You can either setup a server-side proxy or check with your API provider to see if there's a way to get a valid JSONP response.
If you can get valid JSONP, you will also have to setup a callback to handle the response.
In that case, reference the accepted answer for this question.
Have you tried this using $http.jsonp() instead of $http.get(). Also if your using $http.jsonp() then the callback should be set to "JSON_CALLBACK".
e.g.
$http.jsonp('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/33126/JSON?callback=JSON_CALLBACK')
.success(function(data){
$scope.data = data;
}

Backbone model .toJSON() doesn't work after .fetch()

Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});

Syntax refactoring in AngularJS, obtaining correct scope inheritance for data returned by $resource query call?

I am needing the scope of $scope.press to fall within the scope of ReleaseCtrl, wondering the best way to refactor the syntax to do so... I know it's a scope inheritance issue because when I try to post the same console.log($scope.press) below the close of the query function, I get an undefined response as opposed to the array, which properly shows up within the bounds of the "Release" query function.
app.service('Releases', function ($resource) {
return $resource('http://127.0.0.1:3000/json', {}, {
'query': {method: 'GET', isArray: true}
});
});
app.controller("ReleaseCtrl", function (Releases, $scope){
Releases.query(function(data, $scope){
$scope.press = data;
console.log($scope.press);
for(var i=0;i<$scope.press.length;i++) {
console.log($scope.press[i].name)
}
});
$scope.loadRelease = function() {
console.log("Loading Press Release");
}
})
I imagined the Releases.query function could find its way to replace the function directly above it, but, Releases of course is undefined at that point because it has not yet been passed / injected.
I think this is fairly simple to fix, but I do not know exactly the best way to go about it.
Best regards,
Sean
Here is what I ended up doing:
app.service('Releases', function ($resource) {
return $resource('http://127.0.0.1:3000/json', {}, {
'query': {method: 'GET', isArray: true}
});
});
app.factory ('release', function (Releases){
return Releases.query();
})
app.controller("ReleaseCtrl", function (release, $scope){
$scope.press = release;
console.log($scope.press);
$scope.loadRelease = function() {
console.log("Loading Press Release");
}
})
After looking around, I believed injecting with service was better practice than what I was doing earlier, so I just refactored it that way. I think re-writing what is in the service within the factory is even better. Will update when I get there.
A thing to note: Whatever you query must have more than one result. Otherwise it comes back as an object, not an array, and it does not work correctly. Maybe somebody can explain why?
Since you are passing $scope as a parameter to the function you pass to .query, and because .query does not call the callback with any arguments, $scope is probably undefined.
You need to use the following syntax for accessing your resources:
var data = Releases.query(function () {
$scope.press = data;
// ... Further operations with data.
});
See usage note in the docs