Create list of items of a single item at once - angularjs

Angular task 1.5.x:
I have object like this:
{
id: 1,
name: "a",
items: [
{"holiday": "false", "day": "monday"},
{"holiday": "true", "day": "tuesday"...}
]
}
I want a new object to be created in the above way with click of a single button. Note I dont want to add each item separately, all at once. Means, for a single object with name "a", I want to add all items for all days at once.
I can make it work but I want to know the correct way.
ultimately we should be able to create a javascript object in the above format(without id)(I think this format is correct) and send it to server so it will work. But how to add html/angular code so I will get an object that way.
Please let me know for more info.

When using ng-model you do not have to fully define your object in order to have it constructed. E.g.:
Controller
$scope.object= {
items: []
};
var n = 7;
for (var i = 0; i < n; i++)
$scope.object.items({});
HTML
<input type="text" ng-model="object.name"/>
<div ng-repeat="currObj in object.items">
<input type="text" ng-model="currObj.holiday" />
<input type="text" ng-model="currObj.day" />
</div>
The general structure must be defined beforehand, but you do not have to initialize all the properties. They will receive values when binding is triggered (view -> model).

You can do like this :
Create a button in your view and use ng-click directive to capture on click event.
Html:
<button ng-click="createCopy()"></button>
Use angular.copy to create a deep copy of the source object.
This is what angular.copy does as explained in the docs :
Creates a deep copy of source, which should be an object or an array.
If no destination is supplied, a copy of the object or array is
created. If a destination is provided, all of its elements (for
arrays) or properties (for objects) are deleted and then all
elements/properties from the source are copied to it. If source is not
an object or array (inc. null and undefined), source is returned. If
source is identical to destination an exception will be thrown.
Controller:
$scope.mainObject = { id: 1, name: "a", items: [{"holiday": "false", "day": "monday"}, {"holiday": "true", "day": "tuesday"...}] };
$scope.createCopy = function (){
$scope.copyObject = angular.copy($scope.mainObject);
}

Related

Angular ng-repeat rendering issue for small lidt

I have the 2 of objects below:
$scope.MyObj_1={
Id:"1",
Title:"Title1",
Items:[
{
Id:"1",
Comment:"Simple comment 1",
}
]
};
$scope.MyObj_2={
Id:"2",
Title:"Title1",
Items:[
{
Id:"2",
Comment:"Simple comment 2",
},
{
Id:"3",
Comment:"Simple comment 3",
},
{
Id:"4",
Comment:"Simple comment 4",
}
]
};
And I have this html template (just to simplify):
<ul>
<li ng-repeat="note in MyObj.Items" >{{item.Comment}}</li>
</ul>
When I set MyObj with MyObj_1 value and then I set MyObj with MyObj_2 I am getting rendering problem related to the slowness of ng-repeat. In fact ng-repeat starts by adding items of MyObj_2 and then removes the item related to MyObj_1.
I tried ng-cloak and $timeout but the behavior still the same.
I am wondering why ng-repeat did not remove old element first and then push new elements.
Angular.copy makes clone of object from source to destination.It deletes all objects from destination object and then copy properties from source.
Angular.merge appends the source object to destination.If destination object already has elements, it will remain there and new properties from source object will add to destination object.
The behavior is expected if you set the $scope.MyObj_2 = $scope.MyObj_1;
Then they will point to the same reference in memory.
What you need to use is angular.copy() which creates a deep copy of source like this
$scope.MyObj_2 = angular.copy($scope.MyObj_1);
Also, in the repeat you have a typeo, should be
<ul>
<li ng-repeat="note in MyObj.Items" >{{note.Comment}}</li>
</ul>

capturing the form data inside the Angularjs controller

I am new to Angularjs. I am having the form data which I need to make a post request to the server passing the data. I have done the UI and controller part inside the angularjs but do not know how to capture the form data. Please find the link to plnkr - Plnkr link
By clicking the add button, a new li element gets added and the same gets deleted when the minus sign is clicked. I need to get all the key value items into the below format for sending for Post request.
{
"search_params": [
{
"key": "search string",
"predicate": "matches",
"value": "choosen text"
},
{
"key": "search string",
"predicate": "not-matches",
"value": " search value"
},
{
"key": "search string",
"predicate": "matches",
"value": " search value"
}
]
}
How to capture the form data and construct the param object inside my controller inside the searchParams function inside the controller. Please let me know as I am new to Angularjs.
Updated Question
Based on the inputs, I am able to get the user details in the controller. But there are few things:
By default there will be one li element and when the user submits, the current li elements data should be captured in the controller.
Only when I add the criteria using the plus button, the array is getting updated, but the last elements data is not being updated in the model when submitted.
The same is holding good for the deleting the criteria too.
Link to updated Plunker - Plnkr Link
Expanding on #Chris Hermut and assuming you want an array of map, according to json you posted. You can do that by
var arr = [];
var form = {
name: 'asd',
surname: 'aasdasdsd',
wharever: 'asd'
}
arr.push(form);
//prentending to be another (key,value)
form.surname = 'hfg';
arr.push(form);
here's a fiddle illustrating just that.
Directives like <select>, <input> require ng-model attribute to correctly bind your input to $scope properties.
In your HTML markup you'll have to update your form elements with required attributes (like ng-model).
I would recommend (in controller/link) to use only one object for form data with different properties like
var form = {
name: '',
surname: '',
wharever: ''
}
Corresponding <input> would be ex. <input ng-model="form.name" type="text">
After you have your 'form' object populated you can do JSON.stringify(form) before your request (if your using some other content-type then application/json).

extracting information from array using knockout

I currently have an array being passed into my function and i wanted to pull out the information from the array so i can display it on the page.
This is what the array looks like:
EducationalClasses:[object, object]
first object contains:
classId: "324342",
className: "English 101"
second object contains:
classId: "231243",
className: "Reading"
when i do educationalClasses[0] i get the results as in first object. I wanted to create some sort of loop so that in my view page when i have:
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className></div>
<!--/ko-->
i would get English 101 and Reading displayed
This is what i have for my viewModel:
viewModel = function(educationalClasses){
....
self.className= ko.observable(educationalClasses.className); // what i want
}
How can i do this properly and so that all the items in the array are displayed without me having to use educationalClasses[0].className...educationalClasses[1].className
Technically, you don't need any observables for what you're doing here. You just need your viewmodel to have a member named educationalClasses that is an array (or observableArray). You can just wrap your raw data in an object, label it, and it goes.
If you want to change the array and have the view show the updates, you'll want an observableArray. If you want changes to the individual data items to show, you'd want them to be observables as well.
rawData = [{
classId: "324342",
className: "English 101"
}, {
classId: "231243",
className: "Reading"
}];
viewModel = function(educationalClasses) {
return {
educationalClasses: educationalClasses
};
};
ko.applyBindings(viewModel(rawData));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className"></div>
<!--/ko-->

Working with angular cached array object

So I create a cached json object within an array with the following method in Angular:
$scope.saveClaim = function() {
//always set isOffset to false - empty string does not work for non-string objects in web api when field is required
$scope.claimInfo.isOffset = false;
$scope.claimsSubmit.push($scope.claimInfo);
//clears scope so form is empty
$scope.claimInfo = {
id: "",
benefitId: "",
isSecIns: "",
isNoResId: "",
expenseTypeId: "",
fromDate: "",
toDate: "",
provider: "",
who: "",
depId: "",
age: "",
amount: "",
comments: "",
isOffset: ""
};
}
The idea is the user fills out a form, and at the end either selects to add another claim or submit a claim (the object). After each time the form is filled and user selects file or add another, the form clears and the user then enters more data. The results is an array of object(s) that look like:
[
{
"id": "",
"benefitId": "",
"isSecIns": "",
"isNoResId": "",
"expenseTypeId": "",
"fromDate": "",
"toDate": "",
"provider": "",
"who": "",
"depId": "",
"age": "",
"amount": "",
"comments": "",
"isOffset": false
}
]
If more than one claim is entered, then we get multiple objects with same properties.
Each claim is then displayed with limited data in info boxes that display only 3-4 of the properties.
So I am trying to figure best way to do 3 things. First, add a unique "id" to each object. Second, if the delete icon in the info box selected, then remove that object from the array and if the "edit" icon is selected in the info box, then all the relative properties that that object in the array is populated back to the form.
Googling best tries for this, but not sure how I can work with the json objects this for for now. Can some of you help me on this?
Thanks much.
Hard to give the best way. Probably comes down to your style and preferences. But here is one way to do it, to get you going.
Define your model. It will contain the claim that is bound to the form and an array of added claims.
$scope.viewModel = {
claim: {},
claims: []
};
Add a function that assigns a claim object with default values:
var resetClaim = function() {
$scope.viewModel.claim = {
name: '',
city: ''
};
};
resetClaim();
The form elements will use ng-model:
<input type="text" model="viewModel.claim.name">
We will use ng-repeat to show the added claims:
<tr ng-repeat="claim in viewModel.claims">
Our form will have two buttons:
<button type="submit" ng-click="saveClaim()">Save Claim</button>
<button type="button" ng-click="cancel()">Cancel</button>
The cancel button will just reset the form.
The saveClaim function will look like this:
$scope.saveClaim = function() {
if (!isValidClaim()) return;
$scope.viewModel.claim.id ? updateClaim() : saveNewClaim();
resetClaim();
};
The isValidClaim function just checks if we have entered the requied fields. You could use form validation for this instead.
In this solution when saving a claim it could either be a new claim or an existing one that we have edited, and what we will do in the two cases will differ, so we need a way to tell what we are doing. Here we just check if it has an id. If it hasn't - it's a new claim. If it has, it's an existing.
To save a new claim we will do the following:
var saveNewClaim = function() {
var newClaim = angular.copy($scope.viewModel.claim);
newClaim.id = id++;
$scope.viewModel.claims.push(newClaim);
};
Note that it's important that we use for example angular.copy to create a new copy of the claim that is bound to the view. Otherwise we would just push a reference to the same object to the claims array which is not good since we want to reset one of them.
In this example id is just a variable starting at 0 that we increment each time we create a new claim.
Each element in our ng-repeat will have an edit and a remove icon:
<tr ng-repeat="claim in viewModel.claims">
<th>{{claim.id}}</th>
<td>{{claim.name}}</td>
<td>{{claim.city}}</td>
<td><i class="glyphicon glyphicon-edit" ng-click="editClaim(claim)"></i></td>
<td><i class="glyphicon glyphicon-remove" ng-click="removeClaim(claim)"></i></td>
</tr>
The removeClaim function simply takes a claim and removes it from the array:
$scope.removeClaim = function(claim) {
var index = $scope.viewModel.claims.indexOf(claim);
$scope.viewModel.claims.splice(index, 1);
};
The editClaim function will make a copy of the claim to edit and put it in the variable that is bound to the form:
$scope.editClaim = function(claim) {
$scope.viewModel.claim = angular.copy(claim);
};
You can also do the following:
$scope.viewModel.claim = claim;
And when you edit the claim in the form it will update in the ng-repeat at the same time. But then you have no good way of canceling and the save button wouldn't be needed. So it depends on how you want it to work.
If you edit the claim in the form now and save, we will come back to the saveClaim function:
$scope.saveClaim = function() {
if (!isValidClaim()) return;
$scope.viewModel.claim.id ? updateClaim() : saveNewClaim();
resetClaim();
};
This time the claim will have an id, so the updateClaim function will execute:
var updateClaim = function() {
var claim = $scope.viewModel.claims.filter(function(c) {
return c.id === $scope.viewModel.claim.id;
})[0];
angular.extend(claim, $scope.viewModel.claim);
};
It will retrieve the claim that we are editing from the claims array based on the id. We need to do this since we used angular.copy earlier and have two difference objects.
We will then use angular.extend to move all the new edited values to the claim that we pressed edit on in the ng-repeat.
Demo: http://plnkr.co/edit/yuNcZo7nUyxVsOyPTBEd?p=preview

In AngularJS, is it possible to filter inside of a specific element of an array using only a view?

I've got some data like this:
people = [
{
names: [
{first: "Joe", last: "Smith"},
{first: "Joseph", last: "Smith"},
...
]
},
...
]
In other words, an array of objects with an array of names. For example, a person could be called "Joe Smith" or "Joseph Smith". How can I use a filter to only search the first element of names? IE: If I typed in "Jo" or "Smith" it would find the first person. But, if I typed in "seph" it wouldn't.
I've been looking at the examples on this page, but there isn't really an example of filtering inside arrays. Here's what I've tried but it gives me an error:
<input ng-model="search.names[0].$">
TypeError: Cannot set property '$' of undefined
Working Code
Input HTML
<input ng-model="searchTerm">
Results
<tr ng-repeat="p in people | filter:searchFunc">...</tr>
Controller
$scope.searchFunc = function(person) {
var firstPersonsName = [person.names[0]]; // Wrapping in array since the 'filter' $filter expects an array
var matches = $filter('filter')(firstPersonsName, $scope.searchTerm); // Running firstPersonsName through filter searching for $scope.searchTerm
return matches.length > 0;
}
Plunker Demo
Answer to the question in your title
I played around with filter and it doesn't seem like you can go beyond one level deep when specifying a pattern object for it e.g. ng-model="search.names" works but ng-model="search.names.otherVal" doesn't.
Also, even if filter supported going beyond one level deep, you still wouldn't be able to do ng-model="search.names[0]". This is because filter expects the input to be an array, but the elements of your names array are all objects e.g. people[0].names[0] == {first: "Joe", last: "Smith"} so filtering will never work.
The only way to do what you are asking purely through the view and no extra code in your controller is to just create your own custom filter that handles your case.
Would this do the trick?
Say that your input is
<input ng-model="search.name" type="text">
Then, you can display results like this:
<div ng-repeat="person in people[0].names | filter: alias">...</div>
Controller:
$scope.alias = function (object) {
if (object.first.match(new RegExp($scope.search.name))) {
return true;
}
return false;
};

Resources