Angular : Getting values of check box when it is checked - angularjs

This is my view I want to get the values such as diabetes , or htn etc cause I want to store them in a string format. But the way I am dooing it right now I get it in an object format
font(color ='green', size ='3')
strong Past History
.checkbox
label
input(type='checkbox', value='',name = 'diabetes', ng-model = 'formData.history.diabetes')
| DIABETES
.checkbox
label
input(type='checkbox', value='',name = 'htn', ng-model = 'formData.history.htn')
| HTN
.checkbox
label
input(type='checkbox', value='',name = 'asthma', ng-model = 'formData.history.asthma')
| ASTHMA/COPD
Now in my controllers when I
console.log($scope.formData.history)
I get an output like:
`{diabetes : true}`
But I want to send this data to my backend in a String form. Any idea how to get only "diabetes" or "htn" . thank you

The type of the value binded to the checkbox model is by default a boolean. That's why you get true or false as values.
Use the directives ng-true-value and/or ng-false-value if you want to change that. Here is an example, in html:
<input type="checkbox" name="htn" ng-model="formData.history.htn" ng-true-value="'htn'">

By your scenario you should declare data-ng-model as Array.
Your answer is here
<input type="checkbox" ng-model='formData.history[1]' ng-true-value="'htn'">

font(color ='green', size ='3')
strong Past History
.checkbox
label
input(type='checkbox', value='', data-ng-true-value='diabetes', name = 'diabetes', ng-model = 'formData.history.diabetes')
| DIABETES
.checkbox
label
input(type='checkbox', value='', data-ng-true-value='htn', name = 'htn', ng-model = 'formData.history.htn')
| HTN
.checkbox
label
input(type='checkbox', value='', data-ng-true-value='asthma', name = 'asthma', ng-model = 'formData.history.asthma')
| ASTHMA/COPD
Check how I used data-ng-true-value attribute if checked that will contain the value. Similarly you can have data-ng-false-value when it is unchecked. That should give you {diabetes : diabetes}, {htn: htn} But the way you have written your ng-model it will act like radio button if you need multiple selection your ng-model need to be modified to fit the scenario. Hope that helps

JSON.stringify($scope.formData.history)
This should solve your problem if you want your data in a JSON format.

Related

AngularJS ng-options/Typeahead expression syntax

I was trying to find the AngularJS select with ng-options or Typeahead expression syntax but I couldn't find the whole thing in one place, so I gather information from here and there and this is what I came up with:
Expression syntax (This is the full syntax, most of it are optional):
(ObjectForModel) as (stringRepresentation for the UI) for (OneObjectFromList) in (ListOfObjects) | (Filter1) | (Filter2) ...
Example: Lets say we have a list of Students:
var StudentList = [{firstName: "Jhon",lastName:"Smith" id:1},{firstName: "Clint",lastName:"Eastwood" id:2} ];
Lets say that we wanna use this list in a typeAhead input but:
1. We want our popup drop down to display: "first name - last name" but when a user select an item we want the whole item from the list to be populate in the ng-model.
2. We want to filter the select to show only 5 elements
3. We want the pop up drop down list to display only what is relevant base on the user input.
So this is how it looks like:
uib-typeahead="student as (student.firstName +' - ' + student.lastName) for student in studentList | filter:$viewValue | limitTo:5"
If you guys have something more to add please do, I know I could have use it...
You can also change the template ( for example displaying a field in a particular way, and on click set the input with another one )
in the html file :
<script type="text/ng-template" id="deterFormACTemplate.html">
<a ng-bind-html="match.model.displayed | unsafe"></a>
</script>
<input typeahead-template-url="deterFormACTemplate.html"
uib-typeahead="item as item.field for item in autocomplete(...)"
typeahead-on-select="mymodel=$model.field;"
typeahead-wait-ms="500" />
in the controller
$scope.autocomplete = function ( ){
return [ {'field':'..', "displayed":"..."},{'field':'..', "displayed":"..."}, .. ];
}

How to filter a certain object property value with angular select box

I would like to filter out a object that has a property value of "None". The object CounterParty has 2 properties, CounterPartyId and CounterPartyName.
The first object in the db has CounterPartyName: "None", I do not want this to show in the select box options.
I setup a plunker but the select-box is not working and there are no errors in the console:
Plunker
<select ng-model="search.CounterParty"
ng-options="c.CounterPartyName as c.CounterPartyName for c in counterPsList | unique: 'CounterPartyName'">
{{c.CounterParty}}
</select>
Json
$scope.counterParties = [
{"$id":"1","CounterPartyId":1,"CounterPartyName":"None","Documents":null},
{"$id":"2","CounterPartyId":2,"CounterPartyName":"CounterParty A","Documents":null},
{"$id":"3","CounterPartyId":3,"CounterPartyName":"Counter Party B","Documents":null},
{"$id":"4","CounterPartyId":4,"CounterPartyName":"Counter Party C","Documents":null},
{"$id":"5","CounterPartyId":5,"CounterPartyName":"Counter Party D","Documents":null}
];
You don't need to use angular-ui's unique filter here - its purpose is something else.
If you just need to filter out based on a certain property, you could specify the filter expression like so (notice the !):
ng-options = '...in counterPsList | filter: { CounterPartyName: "!None" }'
plunker

Issue on prepopulating model value on view init in angularJS

I want to prepopulate an input field from my controller:
Here is the input field:
<input class="form-control" type="text" name="partnerName" placeholder="Completeaza numele partenerului" ng-model="partnerNameModel.field" required validate-field="partnerNameModel">
In my controller,
If I do this:
partnerNameModel.field = 'test';
I get the following error:
TypeError: Cannot set property 'field' of undefined
So, I had to do it like this:
$scope.partnerNameModel = {field: 'dsad'};
I this good practice?
Is there a better way to prepopulate fields?
You can create the object partnerNameModel by doing
$scope.partnerNameModel = {}
at the top of your controller then you can use the dot syntax to set values like
$scope.partnerNameModel.value = "foo"
$scope.partnerNameModel.bar = "lemons"
This is how I personally work with objects in Angular
When you are dealing with an input that has a placeholder, it makes sense to put no default value.
However, the object you are using must be created or it will be a big pain in the ass.
I recommend that you simply use:
$scope.partnerNameModel = {};
Make sure to initialize your fields that don't use a non-empty default value (a dropdown as an example).
$scope.partnerNameModel = {
myDrop: $scope.myList[0]
};

Angularjs how to set the default value for select

I have the following object:
defaults = {
0 : {
id : 10,
value : "string 1"
},
1 : {
id : 22,
value : "string 2"
}
}
I want to iterate over this object and display it as a select box.
<select ng-model="selectedValue" ng-options="obj.id as obj.value for obj in defaults">
<option value="">---Select option-----</option>
</select>
What I'm trying to achieve is to select 'string 2' by default. But it does not work.
The problem I have is the fact the selectedValue is a string:
$scope.selectedValue = "string 2";
From what I learned from the documentation the selectedValue must be the same object. But unfortunately, it is not possible. In my case selectedValue must be a string.
In other words I need to operate with the name of the option only, I don't care about id.
I tried to use ng-repeat. It even works but displays an empty option and I don't think using ng-repeat is a good way to do it.
Any advice will be appreciated greatly.
If you want the selectedValue variable to contain the value, and not the ID, then you should not use obj.id as obj.value, but obj.value as obj.value.
Selected value should be id;
$scope.selectedValue = 22;
See Demo
EDIT:
change template
<select ng-model="selectedValue" >
<option value="">---Select option-----</option>
<option ng-selected="selectedValue == obj.value" value="{{obj.value}}" ng-repeat="obj in defaults">{{obj.value}}</option>
</select>
see Updated Demo
I think you misinterpreted the documentation.
Selected value should refer to a value of the same object, not be an object itself.
Thus, you can set the default value as :
$scope.selectedValue = $scope.defaults[1].value;
That way, the default value will be set - it does not matter if the value is a string or a number.
If you are using ng-repeat with options you need to use on-last-repeat on your options tag. For example
select name="repeatSelect" id="repeatSelect" ng-model="usertypes.SelectedId"
option ng-repeat="option in usertypes.AvailableOptions" value="{{option.Id}}" ng-selected="option.Id === usertypes.SelectedId" on-last-repeat>{{option.Name}}
select

AngularJS adding 2 properties to associated collections

1. I have a Truck class that has a collection called AxleTypes with the following markup:
public class AxleType : Entity
{
public string Description { get; set; }
public string Type { get; set; }
}
2. My angular form includes the following (to keep this as short as possible I omitted the form's other axle types, and I am using $parent, as this is a template and on main form thru ng-include):
<label for="frontAxles">Front Axle: </label>
<input ng-model="$parent.frontAxleType" type="hidden" value="Front">
<select ng-model="$parent.selectedFrontAxle" ng-options="axleType.Description for axleType in axleTypes">
<option value="" selected>Select Axle Type ..</option>
</select>
3. The main form inserts a new truck via the truck controller, so in the truck controller:
a. I instantiate an instance of the AxleTypes collection so the form is populates the select w/axle types.
b. I instantiate an instance of AxleType to pass the selected data from the form.
c. I pass the respective ng-models on the form to the AxleType variable.
d. I add that AxleType variable to the Truck's AxleTypes collection.
a: if ($scope.axleTypes == undefined || !($scope.axleTypes.length > 0))
{ $scope.axleTypes = API.GetAxleTypes(); }
b: $scope.axleType = {};
c: var frontAxle = $scope.axleType;
frontAxle.Description = $scope.selectedFrontAxle;
frontAxle.Type = $scope.frontAxleType;
d: newTruck.AxleTypes = [
angular.copy(frontAxle)
];
When debugging this is the end result:
To keep this as short as possible I did not illustrate the 2nd axle type select above. But as you can see, the server is picking up 2 axle types however, both properties for each [Type & Description] are null.
Does anyone have any suggestions?
In console.log both values are "undefined".
An interesting observation:
When I hard code the values in the TruckCtrl, everything works fine:
frontAxle.Description = 'Some Front Value';
frontAxle.Type = 'Front';
rearAxle.Description = 'Some Rear Value';
rearAxle.Type = 'Rear';
newTruck.AxleTypes = [
angular.copy(frontAxle),
angular.copy(rearAxle)
];
This would lead someone to think the problem lies with the ng-model on the axle template. However, when I only had one property, ie Description, and not Type in the server class, AxleType, and merely added the select's description via:
newTruck.AxleTypes = [
angular.copy($scope.selectedFrontAxle),
angular.copy($scope.selectedRearAxle)
];
The values passed. Very confusing.
SOLVED !!!
There is alot I would like to say to the 40 some odd eyeballs who perused this problem with no input, and Stewie, well, we know what Stewie is. But I won't. Instead I offer help to those who have this same problem.
OK, on to the solution.
Problem #1: Angular does not accept default values in html inputs.
I was confused why I had an input like so:
<input ng-model="$parent.selectedRearType" type="hidden" value="Front">
and yet angular said it had no value.
SOLUTION TO PROBLEM #1:
You need to initialize the following in your controller:
$scope.selectedFrontType = 'Front';
$scope.selectedRearType = 'Rear';
Problem #2: How do you pass values of multiple properties in a collection?
Despite how real-world this scenario is, it is unsettling that there is ZERO documentation on the matter.
SOLUTION TO PROBLEM #2:
In my html I had this select statement:
<select ng-model="$parent.selectedFrontAxle" ng-options="axleType.Description for axleType in axleTypes">
Where I erred was thinking this ng-model was STRICTLY the Description property of the class AxleType (see my class model above). That was a huge mistake, it was not. That ng-model was not the Description property of the class but actually the entire class itself. So when examining that select's ng-model, realize it is the AxleType class in its entirety, even if only Description property is provided. So what ng-model was giving me was this as a return value in my controller after the user made a selection:
AxleType class => Description = "Whatever the person selected", Type=""
With that being the case, I needed to fill in the blanks angular did not have, namely in this scenario, the Type property.
Here's the whole solution:
// beginning of controller when it initializes
$scope.selectedFrontType = 'Front';
$scope.selectedRearType = 'Rear';
// $scope.axleType = {}; -> NOT NEEDED
// in the save method
// axles
var frontAxle = $scope.selectedFrontAxle;
frontAxle.Type = $scope.selectedFrontType;
var rearAxle = $scope.selectedRearAxle;
rearAxle.Type = $scope.selectedRearType;
newTruck.AxleTypes = [
angular.copy(frontAxle),
angular.copy(rearAxle)
];
I hope I have helped someone!

Resources