I have an angular controller whereby I'm trying to look through a list of strings, querying an ajax query for each string within the list. The code is as follows:
var itemsliststrings = ["department", "year", "project", "subdepartment"];
itemsliststrings.forEach(function (itemStr) {
$http.post("/Budget/GetListBudget", { budgetType: itemStr })
.success(function (data) {
var the_string = itemStr;
var model = $parse(the_string);
model.assign($scope, data);
$scope.$apply();
})
.error(function (error) {
console.error(error);
toastr.error('An error occured, unable to load ' + itemStr);
});
});
This is the code that doesn't work. it complains with the error '$parse' is undefined. I took this example from a SO post.
I basically want to be able to loop through my itemsliststrings, post the string to an web method, and set the return data for this to a model variable called that particular string. So when I take the "department" string, I submit this string to the web method, I get a data object back, which I then set to the $scope.department object.
Thanks
Have you tried just $scope[itemStr] = data?
Did you inject the $parse provider in your controller?
.controller('yourController',function($scope,$parse,etc..){});
Related
I have a table built up in JavaScript thus:
oTable.bindItems({
path: oQuery,
template: this.getFragment("<fragment>"),
filters: aFilter
});
Is there a way to catch the errors coming back from the odata call in the same way when you do an oModel.read you can specify success and error functions?
This reference seems to not mention it: https://sapui5.hana.ondemand.com/#docs/api/symbols/sap.ui.base.ManagedObject.html#bindAggregation
Perhaps there is something I am missing.
We have 2 methods to check for oData Failure:
attachMetadataFailed. (https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.model.odata.ODataModel.html#attachMetadataFailed)
attachRequestFailed.
Let's take up option 2 with an example ( as I'm sure you will have a valid oData Service).
Service: http://services.odata.org/Northwind/Northwind.svc/
Note: Employees is a valid Entity Set in the above Northwind service.
I will try to bind my table with a wrong Enity set name such as : MyEmployees.
Now, binding my table to MyEmployees will throw error which we need to catch. Below is the working code:
View:
<Table items = "{/MyEmployees}">
Controller:
var url = "proxy/http/services.odata.org/Northwind/Northwind.svc/";
var oDataModel = new sap.ui.model.odata.ODataModel(url);
oDataModel.attachRequestFailed(function(e) {
console.log('request failed');
});
this.getView().setModel(oDataModel);
Go ahead and try it. Let me know if this helps. :)
I'm experimenting with Zendesk apps but I'm having an issue passing variables / an array of json objects from my app into the view. I did the getting started tutorials and looked at the API but I can't seem to find an answer.
Here is what I have:
this.ajax('fetchExternalData', myURL).done(function(data) {
this.switchTo('requester', data);
});
but whenever I try to access data in the app, it says it's undefined (data is an array of objects here).
I even tried something like:
this.ajax('fetchExternalData', myURL).done(function(x) {
this.switchTo('requester', x);
});
Where x is just some plain text.
if I do:
this.ajax('fetchExternalData', myURL).done(function(data) {
data = data[0];
this.switchTo('requester', data);
});
I can access properties in data by their name (eg. {{CustomerName}}) but I still can't reference the data var itself.
According the Zendesk site :
this.switchTo('hello', {username: currentUser});
The first argument specifies the template to render, hello, which references the hello.hdbs file in the templates folder. The second argument specifies the data to pass to the template, expressed as a JavaScript object literal, {username: currentUser}. The current user's name is passed to the template to be displayed in the user interface.
So just try like that :
this.ajax('fetchExternalData', myURL).done(function(data) {
//this.switchTo('requester', data);
this.switchTo('requester', {data : data} );
});
I hope this will resolve your issue !
This is my server-side code that adds data to db:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,UsersLanguage,OtherLanguage,Notes,Difficulty")] Word word)
{
if (ModelState.IsValid)
{
word.LastReviewed = DateTime.Now;
word.NextReview = DateTime.Now;
word.OwnerName = User.Identity.Name;
word.ReviewInterval = 0;
if (String.IsNullOrEmpty(word.OwnerName))
return View(word);
db.Words.Add(word);
db.SaveChanges();
return RedirectToAction("Create", new { addingSuccess = true });
}
return View(word);
}
I want to add some data to database using javascript. So I wrote this:
$.ajax({
type: "POST",
url: "/Words/Create",
data: { "UsersLanguage": questionToAdd, "OtherLanguage": answerToAdd }
}).success(function (data) {
console.log("Added");
$(this).parent().fadeOut(1000);
}).fail(function (data) {
console.error("cannot add word");
});
The problem is: this javascript code actually doesn't work. I'm getting error: "The required anti-forgery form field [...] is not present".
I think the reason is I have to send to server exactly the same object as server's "Word". OK, I could make variable in javascript that will look like "Word" class, but what if I once wanted to change "Word" class on my server? I would have to jump through all my scripts that send "Word" to server and change these js objects.
How to avoid that? How could I send some data without knowledge about how Word class is built? How can I send this "Word" to server without all data and make server to create missing variables?
You need to pass the AntiForgeryToken, you can do this creating a form with the tolken and pass it in you data:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken()
}
<script type="text/javascript">
$.ajax({
type: "POST",
url: "/Words/Create",
data: { "UsersLanguage": questionToAdd,
"OtherLanguage": answerToAdd,
"__RequestVerificationToken": $('input[name="__RequestVerificationToken"]'.val()}
}).success(function (data) {
console.log("Added");
$(this).parent().fadeOut(1000);
}).fail(function (data) {
console.error("cannot add word");
});
</script>
I think I found the problem, I had to send something like AntiForgeryToken and I've done this basically the same way like in best answer here:
include antiforgerytoken in ajax post ASP.NET MVC
I don't know if it's the best way, but actually it works ^^
You can not send an object without knowing how it is built.
Why would you change class?.
Generally, in any form creating object WORD in the MVC, should be built by
#Html.EditorFor (word => word.Id)
so how do you change the word class, you will also have to change all the forms. As for the problem: You can expand the object word, but if you not send new properties, will always null.
As for the script: if your form is created using EditorFor (), input element in HTML always have id attribute equal named property. You can write a nice generic js function that will retrieve all the fields from the form and on the basis of selectors build parameter "data" and send to the Controllers.
I'm trying to write a function to remove an answer:
// Remove an answer
$scope.removeAnswer = function(answer) {
Answers.remove(answer._id);
};
However, I am throwing the console error:
DELETE http://localhost:9000/api/answers?0=5&1=4&10=7&11=4&12=2&13=c&14=0&15=0&16=0&17=0&18=0&19=0&2=7&20=0&21=0&22=0&23=4&3=3&4=d&5=0&6=1&7=4&8=2&9=d 404 (Not Found)
When I console.log(answer._id), I get a reasonable id like 348374831...
Why is it converting the id to a weird format and how can I fix it?
Here seems to be an identical question, although the answer doesn't really explain the problem: AngularJS resource - encoding url string parameter as an array
The corect way to do it is:
$scope.removeAnswer = function(answer) {
Answers.remove({
id: answer._id
});
};
or instead of id use the corect name you used in the $resource factory definition.
Example:
var User = $resource('/user/:userId', {userId:'#id'});
User.get({userId:123}, function(user) {
user.abc = true;
user.$save();
});
$resource expects object parameter. Here's an example in Angular docs
Trying to pull data from parse.com and use underscore.js I tried using this to build a table of the data. When I run it with hard coded json it works but when I try running it with pulled data returns an empty table.
Parse.initialize("", "");
var allDeals = Parse.Object.extend("Deal");
var query = new Parse.Query(allDeals);
query.find({
success: function(results){
var deals = JSON.stringify(results);
var template = $("#usageList").html();
$("#target").html(_.template(template,{deals:deals}));
},
error: function(error) {
alert('something was wrong');
}
});
Thanks in advance!
Like #mu said it would be easier to see whats in results..
But I have run into this with Parse before. Taking a guess.. You can try this
$('#target').html(_.template(template, { deals: results.models }));
"results" is a backbone collection and "models" holds the array of objects you are after.
Presumably you're getting a JavaScript object of some sort in results in your success callback. Then you serialize that to a JSON string with:
var deals = JSON.stringify(results);
That leaves you with a string in deals and your template probably doesn't know what to do with a string, it probably wants an object or whatever was in results in the first place. Try skipping the stringification and just feed results straight into the template:
$('#target').html(_.template(template, { deals: results }));