AngularJS - append data to json array - javascript

I am stuck in one scenario where i have to pass data from one controller to another controller.
My app works like this:
View 1 -> gets some users from json array and displays in a table.
When i click add user in View 1, i get redirected to view 2.
View 2 -> has 2 input fields and a button (to add a new user).
When i redirect to view 1, i want the new user to get appended but this is not working.
To make it easy, i have demoed this here - http://plnkr.co/edit/yz6mpplZGh4q5bPDO2bc?p=preview
Any help is much appreciated.

You are always overwriting the 'users' content on entry of the list controller.
Change your controller to
...
controller('UserController', function($scope,UserService){
if (!$scope.users)
{
UserService.getUsers().then(function(data){
$scope.users = data;
})
}
...
And bring back your 'correct'
$scope.users.push($scope.user)
in your addUserController.

View2 directive needs to define that it requires View1. This will tell Angular to pass the controller for View1 as an argument to View2's controller.
You can then call a method addUser(..) on that controller.
https://docs.angularjs.org/guide/directive#creating-directives-that-communicate

Related

MVC Controller View Javascript and passing values

I have a view that displays both the search screen and the results list. To start the results list is hidden.
On clicking the search button, instead of the view posting back to the controller using a Html.BeginForm, it has a JavaScript event handler which is called.
The Handler passes over a complex object, in the form of:
{ "searchData":
{ "ticketNumberCompare":0,
"ticketSearchTextFrom":"0",
"ticketSearchTextTo":null,
"ticketDateCompare":1,
"startDate":"2017-01-06T00:00:00",
"endDate":"2017-01-13T00:00:00",
...
etc
...
},
"searchMode":
{ "mode":2,
"pageNumber":1,
"pageSize":5,
"sortDirection":"desc",
...
etc
...
"ValidationErrorMessages":null
}
}
By using Json.Stringify, I have got the above structure to be converted for use by a function within the c# MVC 5 controller, defined as follows.
[HttpPost]
public JsonResult GetSearchResultsJson(ComplexObject searchCriteria, int? page)
{
}
This function returns back html which is rendered from a Razor view using a model that contains the results from the database.
When I click on the submit button for the initial search all works and I get a partial view of five records displayed with the correct pageList values displayed.
When I click on the pageList items I get a page not found error.
On checking the ajax call for the initial load it is passing over the Json.Stringify of the structure at the top of this question. But the pageList items are not, they just pass over the page
Addendum:
Oh I forgot to mention that I have upgraded this function to use an object instead of the four string that used to be passed, because a new super search now has around 30 properties. Before the change the code worked fine.

Transfer data from one html to another using AngularJS services (data share between controllers)

I have looked up several posts with similar issue but was unable to find a solution for my case.
I have a search page that sends a request to the backend an populates the page with search results (each result is an object). I display a concise view of each object and, upon a mouse click on a specific object, the user should be redirected to a page that shows a more detailed view for that object.
On my JS side, I have one controller that handles the $http.post call and retrieves the objects from the backend to display on the first page. I use a different controller for the second page to try and get the relevant object from the first controller (through angular's .service ), but for some reason I get an empty object on the second page. The service works with a getter and a setter. The service is able to set the object just fine, through the first controller, and I am able to print it. However, when redirecting to the second page, while using the second controller's getter, the object gets deleted and shows as empty for some reason.
Here is the relevant code. The service:
app.service('shareService', function(){
var savedData = {}
function set(data) {
savedData = data
console.log(savedData);
}
function get() {
console.log(savedData);
return savedData;
}
return {
set: set,
get: get
}
});
The search (setter) contoller:
app.controller('SearchCtrl', function(shareService, $scope, $http) {
$scope.sendSearch = function() {
$http.post("http://localhost:9080/MedNetApp/rest/mednet/searchCollections", json).success(function (response) {
$scope.collections = response.searchResults;
shareService.set($scope.collections);
});
};
});
The second (getter) controller:
app.controller('CollectionsCtrl', function(shareService, $scope){
$scope.collections = shareService.get();
})
Not sure if this is relevant, but here is also the html part where I set up a temporary test button to redirect to the second page:
<button id=mixing type = "button" class="btn btn-primary-aligned"
data-ng-click = "go('second-page.html')">temp</button>
So, at the end, savedDatashows as empty object when printing it the second time through the get() function. Any idea why this is not working? or a better way to send data to a new page?
EDIT - I should mention that I basically relied on this solution:
AngularJS - Passing data between pages
So, after further research, I came across this solution:
Sharing Data between pages in AngularJS returning empty
I used sessionStorage in my service, as described in the link above, and it fixed the problem.
Use localStorage or sessionStorage
var myJson ={};
localStorage.set("your_Data",myJson);
// to get the value from another page
var returnJson = localStorage.get("Your_Data");

Ionic and Angularjs - Update/Refresh View from Controller

The usual start to these, I am new to both Ionic and Angularjs. I am developing an Ionic app which at it's heart is very simple. We show a list of classes(sessions), the person clicks on an icon to book the class then the icon changes to allow them to cancel the class. We also update the card to show the number of places remaining in each session on the day.
I have the code working to add and remove a person to and from a class but I am not sure how to update the template view from within the controller.
The controller code is pretty simple
// Check Person in to session.
$scope.addCheckIn = function(schedule){
var promise = sessionDataService.checkinSession(schedule.sessionID);
promise.then(function(data){
// Update (refresh) Schedule Details
// NOT SURE WHAT TO PUT HERE??
});
};
I have tried a number of different approaches including
Refreshing the $state and calling doRefresh and even calling the original controller methods to populate the cards again but the view won't update unless I physically click between states on the screen
//$state.go('app.schedules', {}, {reload: true});
//$scope.doRefresh();
//getScheduleData(formatDate(selectedDate), formatDate(selectedDate), 'true');
I have also looked at $scope.apply and $scope.timeout but I am not sure if this is taking me further from the real solution
What is the correct way to update the view after an update? Should it be after the promise.then in the controller or should I call a service and update everything.
Any tips on what is the best way to do this and a point in the right would be really appreciated.
Thanks everyone.
In your promise, you should add the data to the scope.
$scope.scheduledetails = data;
Then in your template, you will be able to access the object scheduledetails from the controller with AngularJS brackets to bind the data to the HTML.
<h1>{{scheduledetails.title}}</h1>
<p>Details : {{scheduledetails.details}}</p>
AngularJS should take care of refreshing what is needed without having to call any method or anything.
Full example
Controller
$scope.addCheckIn = function(schedule){
var promise = sessionDataService.checkinSession(schedule.sessionID);
promise.then(function(data){
$scope.scheduledetails = data;
});
};
Template
<h1>{{scheduledetails.title}}</h1>
<p>Details : {{scheduledetails.details}}</p>

having trouble with dynamic segments in emberjs

This should be simple to do. I just can't pass the value of the input to the product-details view. I'm trying to create a unique template page for each item added to the list. Clicking the 'details' link should take the user to the unique page. I understand how dynamic segments works, I'm just getting stuck somewhere.
Thanks!
http://emberjs.jsbin.com/midivu/1/edit?html,js,output
In your link to helper you need to pass the parameter in...
{{#link-to 'details' name class="add-item-button"}}
Example..
If you imagine link-to as a function then in your case it would be
linkTo(route, segment, etc...)
But imagine it this way just to understand the adding parameter...
To fix your Details Route
App.DetailsRoute = Ember.Route.extend({
model: function(params) {
return userList.findBy('name', params.itemName); // assuming you want to find the details by it's name
}
});
This is because you did not create a data store. You are using a global variable as your data store, therefore, you must get it from the global.

Handling 1 json split between controllers in angular

I have a bit of an interesting problem I am trying to currently figure out using angular.
I have 1 json object I need to use split between 2 controllers, I want to be able to change (save new items and delete json) the json in each controller separately. So when I modify something in one controller it just saves that part of the json - not the whole thing.
I will explain this as clearly as I can -
I have a factory that sends the json to both controllers, here's what it looks like(fake json data for now)
.factory("UserService", function($http) {
var LevelsHere = $http.get("/assets/images/generated.json")
.success(function(data){
return data;
});
return {
all: function() {
return LevelsHere;
}
};
})
Each controller then lists it as a dependancy then calls it like so -
UserService.all().then(function(data){
$scope.listTable = data.data;
});
This works great, and the 2way data binding is awesome in this case because if i change something in 1 controller, it changes immediately in the other. My real problem with this is I want to be able to save the content changed in the json in each controller individually.
So, the Json has a parent (name) and 2 children. Each controller has access to the parent and 1 of the children so for example. controller 1 has parent and child 1, and controller 2 has parent and child 2. When I want to click my save function - for example in controller 1 I want to save the json to the backend to overwrite the old stuff but only from the controller I am choosing to save. So Even if i made changes in controller 2, when I save 1, i Just want it to send parent(it's index) and child 1 to overwrite.
I think the problem may root from the fact that I am fully binding the data in each controller to all the the json maybe? Currently I am just trying to send the $scope.listTable back, and it's registering all the changes (between both sections).
Apologies if I rambled on here - I am trying to be as clear as possible. Thanks for taking the time to read!
EDIT I was thinking - and I don't know if this is possible so bear with me - Can it be designated that the json i bring into listTable only binds to what it needs. So for example - controller 1 only binded to all the parent and child 1 (and not child 2). Is this possible?
EDIT 2 Following up on the previous edit - I think I boiled down the question to - can I only save certain parts of the json instead of the whole object. I cannot have it save both child 1 and 2 at the same time because it might overwrite things that are not meant to be saved at that time. so it's either - can I just use the selected pieces of json, or can I just save the selected pieces of json. thanks again for reading!

Categories