Dynamic default values for dynamically generated ng-model - angularjs

I am facing problem in populating default values for dynamically generated form fields in using angular. So, I have a login form that generates itself based on the attribtes returned by aREST interface. Therefore for my html page, I just have :
<li ng-repeat="element in elements">
<label>UserName</label>
<input type="{{element.inputType}}" ng-model="{{element.fieldName[element]}}" required="required"/>
The default values are returned in an attribute called placehoder in elements object. following tag gives an idea of the task that I am trying to achieve
<input type="{{element.inputType}}" ng-model="{{element.fieldName[element]}}" required="required" placeholder="{{element.placeholder}}"/>
Finally, when the user clicks submit , I need to post the default value of text field if it has not been changed.
Any help would be highly appreciated.
Thanks

If you can add/use a library like underscorejs or lodash, then you can use their _.defaults() :
var object = { 'name': 'barney' };
_.defaults(object, { 'name': 'fred', 'employer': 'slate' });
// → { 'name': 'barney', 'employer': 'slate' }
with angular only, you could add a directive to your form, that watches 'submit' and sets the default values for you.

Thanks for replying #nilsK, I am very new to javascript frameworks and Angular is the first one that I am having my hand on.
So in my R&D with it , I solved my issue by adding the two arrays of values i.e. FieldName and Placeholder to the scope object that I use to post data to my backend. I assign values to these arrays from the objects(placeholder and fieldName) that recieve from REST service as:
$scope.user={};
$scope.user.FieldNames=[];
$scope.user.FieldValues=[];
angular.forEach($scope.elements,function(value,index){
$scope.user.fieldValues[index] = $scope.elements[index].placeholder;
$scope.user.fieldNames[index] = $scope.elements[index].fieldName;
})
and on the html form, I bind ng-model to the scope array of values that I want to display as defaults in text field.
<input type="{{element.inputType}}" ng-model="user.fieldValues[$index]" required="required" />
Therefore, the default values are posted if user does not change them and if there is a change, updated values are posted.
Any suggestions to improve this solution are most welcome.

Related

How to get form data in dynamic form in Angularjs?

I have created dynamic form, here I want to send form data to controller. How can do this?
Here is plunker code link https://plnkr.co/edit/xmxDJHTPfJoSFwa2FWCB?p=preview
Issues:
when I change the value then element label also change.
How can I get the form data in product_submit function of controller.
All response appreciated.
Use
<input type="text"
id="module_module"
ng-model="getCol.value"
required="required"
class="form-control col-md-7 col-xs-12"
placeholder="Enter {{getCol.Field}}"
/>
Look here ng-model="getCol.value". You are using filed name as text field model value. Filed name and value are different. That is what you want I suppose.
You can access the values easily from your controller as $scope.getColumn[1].value. Change index or iterate accordingly.
Plunker here
To solve label issues, in your html, I changed ng-model expression to bound into getColumn.Value
In controller, I can read value entered in scope.getColumn[i].Value
I also updated code https://plnkr.co/edit/KlhAb69seMzHsLuhqweR?p=preview

AngularJS dropdown selected values need as JSON

I have multiple dropdowns in my application which are populating through a json (which is a map basically) given in controller.
For first dropdown if I select xyz value, then corresponding xyz1 values should come in dropdown and similarly for third dropdown. This all is happening fine currently. But now I want these user selected values to get in json form so that I can send back to backend for further processing. I am not getting selected values but the wrong second dropdown values if I print on console.
codepen and
working plunker
I understand that you need to get values from the dynamic input elements. For that, you need to set ng-model to the input elements, not to the div.
The below updated part would help.
<div ng-init="pageObjectName.pageObjParam={}" ng-repeat="(key , value) in pageObjectName.pageObjMethod">
<input ng-model='pageObjectName.pageObjParam[key]' value='' placeholder="{{key}} - {{value}}"></input>
</div>
Now you can get those values from $scope.pageObjectName.pageObjParam.
Updated Plunker
EDIT
I hope the above part helped to get value from dynamic input fields. Now I suggest you to update the code block like below to get the selected values from dropdown (ie, use one hidden input field for each select) and you will get what you want.
<select id="pageObj" ng-model="pageObjectName.pageObj" ng-options="key for (key,value) in pageData" ng-change="pageObjectName.pageObjParam.pageObj=pageObjectName.pageObj">
<option value=''>Select Page Object</option>
</select>
<input ng-model='pageObjectName.pageObjParam.pageObj' hidden/>
You can have a look at the same plunker now
Your codepen seems to be confusing and not working. As you already have the implemention for dropdown I will continue from here about how to get the data from the drop down and convert the data into a JSON.
After getting the data from the dropdown create a JSON object and store it.
I have written a small example to show how to store the data.
$scope.selectedState = function(item) {
var output = {};
output.name = item.name;
$scope.viewOutput = output;
};
Update:
I tried hard but could not get the values using angular way. If you are still looking for an answer then we can use basic javascript way. Refer plunker for the same.
$scope.submitMyForm = function() {
/* while compiling form , angular created this object*/
var pgObj = $scope.pageObj;
var pgClass = $scope.pageClass;
var pgMethod = $scope.pageObjMethod;
var pgObjvalue = document.getElementById('pageObj').value;
var pgClassvalue = document.getElementById('pageClass').value;
var pgMethodvalue = document.getElementById('pageMethod').value;
$scope.output = {'object' : pgObjvalue, 'class': pgClassvalue, 'method': pgMethodvalue};
console.log(data);
};
Working Plunker.
P.S: If you figured out the answer using angular way then do let me know after posting it in the answer section.

Best way to get values using ngFormController

This can't be correct, perhaps my google has gone off the rails but for the life of me I can't find any documentation to return all $valid = true values using the FormController. Does this functionality exist? I'm trying to marshall information from a form and send it to my web service but I wan't to make it something sensible before doing so. Currently I'm looping through all the properties in the FormController for a given form and looking to see if it doesn't start with $, and $valid = true and pushing it into an array like so:
angular.forEach(form,function(data,key)
{
if(key.indexOf('$') === -1 && data.$valid)
{
var item[key] = data.$modelValue;
clean.push(item);
}
})
Real basic, but I'm totally stumped (and can't fully believe) that this doesn't exist already in the angular API somewhere. Am I missing something? I'm still learning a lot about angular and am getting the feeling that much isn't really documented but perhaps i'm missing something quite basic. Thanks for reading!
This is not what ngFormController is used for (for validation and custom directive scripting). If you need to collection form data to send to server all you need is do is to make use of ngModel directives:
<form novalidate ng-submit="saveUser()">
<input type="text" ng-model="user.name">
<input type="text" ng-model="user.email">
</form>
and in controller saveUser handler you can access form data like
$scope.saveUser = function() {
console.log($scope.user); // {name: "Thomas", email: "mann#ga.com"}
// use $scope.user data to send to server
};
You just need to use ng-model. Angular won't populate the model until the value in the form is valid, so you don't need to check $valid manually.
Ex:
<input type="text" ng-model="myData" ng-minlength="3" required>
{{myData}}
You'll see myData isn't populated until you've entered at least 3 characters.

ng-model preventing ng-value to be displayed

I'm pretty new to angular world and I have an issue with it.
I'm working with ejs too.
I have an input that I want to fill (value) with an ng-model.
The problem is my model is empty while the user doesn't specify a value.
I want to display a default value when my model is empty. This default value is sending by the ejs (server side). Doing that, I can't set a default value in my controller.
To do so I wrote the following :
<input type="text" ng-model="owner_adress" ng-value="'{{owner_adress || '<%=user.owner_adress%>'}}'"/>
If I look into my code, I can see the value is okay (ejs result when my model is empty, my model value otherwise) but the value is not displayed in my input (ie the user can't see it).
I looked for a work around (ng-cloak was fine but I can't use it in my input field).
Any clue would be nice !
Use ngInit directive instead. If owner_adress is defined in controller it will be used, otherwise it will default to serverside rendered value:
<input ng-model="owner_adress" type="text"
ng-init="owner_adress = owner_adress || '<%=user.owner_adress%>'"/>

angularjs value on load incorrect

See this plunk
I want to use an object model on an input (for interaction with the angularui bootstrap typeahead). It works perfectly when selecting something from the typeahead, but on load it displays [object Object] How can I get the input to display a property of the model object on load?
Just in case someone else landed here just like me, having a [object Object] being displayed in some input(s)...
In my case, I named the form element with the same name of the model property, like this:
<form name="contact">
<input type="text" ng-model="contact.name" />
<input type="text" ng-model="contact.email" />
</form>
Either change the form name to a different name, or change the model name.
As Angular populates the $scope with a property with the same name as the form, it overrides the model instance!
I came across this also and docs don't show how to hook into bootstrap updater callback.
I did it by setting initial value to string. When you type in the field model will be a string. When you select from dropdown it will be object
app.controller('MainCtrl', function($scope) {
$scope.data = [{id:1,name:"google"}, {id:2, name:"microsoft"}];
$scope.selected = '';
$scope.$watch('selected',function(newVal,oldVal){
if(newVal && angular.isObject($scope.selected)){
console.log($scope.selected)
}
})
});
Plunker
Perhaps ther is a better way using directive's attributes but not sure what that is
Turns out there is currently a bug in ui-bootstrap that is fixed in master and will be out soon. I also misunderstood the ui-bootstrap build files and was including both the templated and the non-templated versions in my app.
I monkey patched my ui-bootstrap and switched to templated only and it is now working for me.
see the google group discussion
Angularjs Form showing [object Object] on load in form fields
It occurs only if your form name and ng-model name (value) are same

Resources