Dynamic creation of ng-model in angularjs - javascript

I have property fields that contains string array:
in controller I have:
$scope.data = {};
$scope.fields = [
"new0.name",
"new0.type",
"new0.address",
"new0.city",
"new0.postalCode"
];
in view I have:
<div class="control-group" ng-repeat="f in fields">
<label class="control-label">Some field name</label>
<div class="controls">
<input type="text" name="{{f}}" ng-model="data.f" class="input-xlarge">
</div>
</div>
In the ng-repeat, how can I concatenate value of f to the ng-model to get, for example ng-model="data.new0.name"?

To reference a property of an object with a variable, use bracket notation
data[f]

Related

How to use input field value attribute while using formControlName? [Angular]

What I want to achieve: I want pre-populated data in my form and I also want to use formControlName as I want the data too.
My html file -
<div class="container">
<p class="h4 my-5">Add New Result</p>
<div class="row">
<div class="col">
<form (ngSubmit)="editStudent()" [formGroup]="studentEditForm" name="myForm">
<div class="mb-3">
<label for="roll-no" class="form-label">Roll No.</label>
<input type="number" class="form-control" id="roll-no" name="rollno" formControlName="rollno" value="{{student.rollNo}}" placeholder="{{student.rollNo}}" autocomplete="off" required>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" formControlName="name" value={{student.name}} required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" formControlName="email" value={{student.email}} required>
</div>
<div class="mb-3">
<label for="score" class="form-label">Score</label>
<input type="number" class="form-control" id="score" name="score" formControlName="score" value={{student.score}} required>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm.$valid)">Submit</button><button type="submit" class="btn btn-dark mx-4">Clear</button>
</form>
</div>
<div class="col"></div>
<div class="col"></div>
</div>
</div>
In Input Tag, I want to use value attribute so I can get a default value but I get Empty fields and I think it is because formControlName is controlling the data in my form. Is there a way to get pre-populated data using value attribute along with formControlName attribute?
Placeholder attribute works fine but I want a default value.
if you want a default value simply initialize the form with values, for example:
form = new FormGroup({
name: new FormControl('defaultNameValue'),
email: new FormControl('defaultEmailValue')
})
You should be doing it in you component instead of using value attribute. While defining the form example
studentEditForm= new FormGroup({
rollNo: new FormControl(this.student.rollNo)
})
or if student data is not available at the time of definition then use formcontrol.setValue after you initialize the student data something like
this.studentEditForm.controls.rollNo.setValue(this.student.rollNo)
Using the value and the CVA (Control Value Accessor: formControlName, formControl, and ngModel) to control the value of the input will override each other each time you change anyone of them.
Instead, it's better to rely only on one of them. If the CVA is used, then you can pass an initial value (default value) to the form-control while defining it:
studentEditForm = new FormGroup({
score: new FormControl(YOUR_INITIAL_VALUE),
});
For more info, check here how Angular passes the value from CVA to the value property when using both of them:
default_value_accessor.ts
Used value and CVA to control value
try this :
studentEditForm = new FormGroup({
score: new FormControl(VALUE),
});

Html value attribute having multiple values

I am new to angular js. Now I have an input where I have implemented a token field. Now, the value attribute of the input box has values in an array. Now I don't know how we can use that array in the html. Like
value="abc,pqr"
This works , But I have an array and that array I need to use in the html.
<div class="form-group">
<label for="inputEmail3" class="col-sm-2">Should</label>
<div class="col-xs-5">
<input name="should"
id="should"
type="text"
value=""
placeholder="should requirement"
class="form-control setmargin">
</div>
</div>
$scope.somevalues = ['abc','pqr','hhhh'];
This values are coming from the ajax call. Now I have bootstrap tokenfield so I need to have all this values in that input box . How can I use this array values in the html value atttibute ?
To clarify, you have an array of values coming from an ajax call, but you would like them to be comma-separated as a string?
You want to use the join function. This will combine all the elements in the array into a string, separated by the string as the parameter (in this case, a comma).
var somevar = ['abc','pqr','hhhh'].join(',');
document.getElementById('should').value = somevar;
<div class="form-group">
<label for="inputEmail3" class="col-sm-2">Should</label>
<div class="col-xs-5">
<input name="should"
id="should"
type="text"
value=""
placeholder="should requirement"
class="form-control setmargin">
</div>
</div>
You should describe it better what you want to do.
But, you can join the array: ["abc", "pqr", "hhhh"].join(','), which will give you "abc,pqr,hhhh".
If you want that to appear in your <input>, then add ng-model="value" to it, and populate it in your controller: $scope.value = ...;. Here is a demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.somevalues = ['abc', 'pqr', 'hhhh'];
$scope.value = $scope.somevalues.join(',');
$scope.toArray = function(){
$scope.somevalues = angular.copy($scope.value.split(','));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2">Should</label>
<div class="col-xs-5">
<input name="should" id="should" type="text" ng-model="value" ng-change="toArray()" placeholder="should requirement" class="form-control setmargin">
<div>To string: {{value}}</div>
</div>
<div>To array: {{somevalues}}</div>
</div>
</div>
try to convert tostring() like
$scope.somevalues = ['abc', 'pqr', 'hhhh'].toString();
Copied Snippet from #richard
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.somevalues = ['abc', 'pqr', 'hhhh'].toString();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2">Should</label>
<div class="col-xs-5">
<input name="should" id="should" type="text" ng-model="somevalues" placeholder="should requirement" class="form-control ">
</div>
</div>
</div>

How to pass value from controller to input HTML in angularjs?

How do I pass a value from my controller to <input>tag in my view? I got the data successfully but calling it from the html, it's not working? I don't get any errors, my syntax is just wrong, I tried several syntax base from angularjs documentation, I also tried using ng-value={{data.email}} and even placing double quotes between the value. What is the proper way to do this?
this is my html:
<label class="item item-input">
<input type="text" placeholder="Email" value={{data.email}} disabled>
</label>
this is my controller:
$http({
method: 'POST',
url: 'myservice',
data: encodedString,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
for (i = 0; i < data.length; i++) {
if (data[i].QActivationCode === data[i].token) {
$scope.userData = data[i];
Acct.setAcctEmail(data[i].email);
}
}
});
You can use either ng-model or ng-value. You are using the wrong key in the view i.e. you should use userData.email instead of data.email in the HTML view. (The statement $scope.userData = data[i]; states that you are adding the key userData in the scope not the data):
Using ng-model
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="userData.email" disabled>
</label>
Using value
<label class="item item-input">
<input type="text" placeholder="Email" value={{userData.email}} disabled>
</label>
Since the input field is disabled and we do not need to alter that input field so you should use the 2nd option.
In angular, ng-model is used to bind the scope values with the html elements. Or we can use {{}} expression if we have to pass the value to the input tags.
Small description about ng-model:
The ngModel directive binds an input , select , textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.
Corrected html code is attached below:
1. <label class="item item-input">
<input type="text" placeholder="Email" ng-model="userData.email" disabled>
</label>
2. <label class="item item-input">
<input type="text" placeholder="Email" value={{userData.email}} disabled>
</label>
use ng-model
<label class="item item-input">
<input type="text" placeholder="Email" ng-value="data.email" disabled>
</label>
make sure that object data exist on the scope.

Angular Validation not working when dot in model

Angular validation is working when there is no dot(.) in model in this following code...
<div class="form-group">
<label for="title">Post Title</label>
<input ng-model="new_title" class="form-control" name="new_title" type="text" required/>
<p class="error" ng-show="addForm.new_title.$touched && addForm.new_title.$invalid">This field is required</p>
</div>
But it is not working when I use ng-model="new.title" like in the following code...
<div class="form-group">
<label for="title">Post Title</label>
<input ng-model="new.title" class="form-control" name="new.title" type="text" required/>
<p class="error" ng-show="addForm.new_title.$touched && addForm.new.title.$invalid">This field is required</p>
</div>
Here is what I am using new in my controller
$scope.submit = function(){
var request = CRUD.create($scope.new);
request.success(function(response){
$scope.flash = response.status;
});
};
Help would be appreciated
You should not change your name along with your model.
<div class="form-group">
<label for="title">Post Title</label>
<input ng-model="new.title" class="form-control" name="new_title" type="text" required/>
<p class="error" ng-show="addForm.new_title.$touched && addForm.new_title.$invalid">This field is required</p>
</div>
This is how it should look like.
The validation doesn't check your model. It checks the form model that you bind the scope when using name attribute. So when checking for errors, you use the name attributes of the form and the inputs. You just need to change your name of the input from new.title to new_title.
You can't use dot (.) in variable name. you should use _ or camel-case to declare variable like:
new_title or newTitle
if want to use dot (.) notation then use like
var info = {
title: "your title"
}
then you can use like
<input ng-model="info.title" class="form-control" name="info.title" type="text" required/>
but you cant use new as a variable name. new is a reserved keyword

How to assign values to control using angularjs

I have a detail view and from database only single record is comming, I need to assign data to controls. below is my code
var app = angular.module("MyProductApp", []);
app.controller("ProductsController", function ($scope, $http) {
var ProductID = #Html.Raw(Json.Encode(ViewData["ProductID"]));
$http.get('/api/Products/GetProductForEditOrDetail',{params: { ProductID : ProductID }}).
success(function(data){
$scope.Product = data;
}).
error(function(data){
alert("msg");
});
});
and below is html code
<div ng-app="MyProductApp" class="form-horizontal">
<div ng-controller="ProductsController">
<h4>Product</h4>
<hr />
<div class="form-group" >
<label class="control-label col-md-2">Product Name</label>
<div class="col-md-10">
<input id="txtProductName" type="text" class="form-control" name="txtProductName" disabled="disabled" Value="{{Product.ProductName}}" />
<input id="hdnProductID" type="hidden" class="form-control" name="hdnProductID" value="{{Product.ProductID}}" />
<input id="hdnCategoryID" type="hidden" class="form-control" name="hdnCategoryID" value="{{Product.CategoryID}}" />
</div>
</div>
</div>
</div>
You should use ngModel directive
The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
<input ng-model="Product.ProductName" />
ngModel is what you are looking for, read the docs !
You wanted to pass value with hidden fields, so ng-model would not work in that case, you could use ng-value in that case
<input id="hdnCategoryID" type="hidden" class="form-control" name="hdnCategoryID" ng-value="Product.CategoryID" />

Categories

Resources