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
Related
I am trying to parse data in d3 using the csv function. I am attempting to give each datapoint a new attribute (Region) during processing. Outside the CSV function I defined a function that is supposed to take the datapoint, check to see if the state is Alabama, and if so, assign the Region attribute to a string of either "North" or "South".
var parseRegion = (function(d){
if(d.State === "Alabama"){
return "South";
}
else {
return "North";
}
});
However, when I run the code, every datapoint is assigned a "Region" attribute that is assigned to the function itself. In other words, it is assigned the actual code, rather than the return values. What am I doing wrong??
d3.csv("data.csv").get(function(error,data){
if (error) throw error;
data.forEach(function(d){
d.Deaths = +d.Deaths;
d.Population = +d.Population;
d.Year = parseDate(d.Year);
d.Region = parseRegion;
});
Thanks for any help you can provide. Eventually I will add additional states besides Alabama of course.
Your problem is that you're not calling the parseRegion function that you define.
So you need
d.Region = parseRegion(d);
More generally d3.csv provides a way to parse the data without the use of forEach. You can do the following:
d3.csv("data.csv")
.row(function(d) {
//Code to parse data row by row goes here
})
.get(function(error,data){
//Data is now the whole parsed dataset
});
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
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));
}
});
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
Am looking to read & display this JSON array of objects.
[
{
"pictitle":"title1 ",
"thumbpicurl":"url1",
"bigpicurl":"url2",
"picdescription":"text text"
},
{
"pictitle":"title2 ",
"thumbpicurl":"url1",
"bigpicurl":"url2",
"picdescription":"text text"
},
]
JSON is served by this factory.
angular.module('picService', ['ngResource'])
.factory('picsFactory',function($resource){
return $resource('pictures.json',{},{
'getData': {method:'GET', isArray:true}
}
);
});
This Markup displays mini thumbnails using the thubmpicURL of the JSON data.
<div class="miniImages">
<a href="/home/{{$index}}">
<img src="{{pic.thumbpicurl}}" class='thumbnail'/> </a>
</div>
Am using stateProvider for routing to display enlarged version of the picture when user selects a thumbnail.
$stateProvider.state( 'home/:id', {
url: '/home/:id',
views: {
"main": {
controller: 'picCtrl',
templateUrl: 'home/pics-detail.tpl.html'
}
}
});
First controller returns the JSON picture data.
.controller('HomeCtrl', function HomeController( $scope,picsFactory ) {
picsFactory.getData(function(picturedata){
$scope.picParams = picturedata;
});
})
Second controller is looking to set properties of each picture object. Am not sure what is the correct syntax to set the stateParams to the picture object.
.controller('picCtrl', function picController( $scope, $stateParams ) {
$scope.picture = $scope.picParams[$stateParams.id];
})
;
I get this error in the debuge console. I think it doesn't like my $scope.picParams[$stateParams.id] in picCtrl controller.
Is this the correct way to make use of $stateParams
TypeError: Cannot read property '0' of undefined
--
ANSWER:
I modified picCtrl to inject picsFactory and with this change it looks to work now.
.controller('picCtrl', function picController( $scope, $stateParams, picsFactory ) {
picsFactory.getData(function(picturedata){
$scope.picture = picturedata[$stateParams.id];
});
})
;
The reason for this could be that the async call of getData on HomeCtrl may not be complete before your second controller picCtrl is initialized and hence picParams is null.
Also HomeCtrl should be parent state or declared on parent html of ui-view for the picCtrl to be able to access what has been set by HomeCtrl