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.
Related
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),
});
Currently I have two directives in the app.js, which are for following onkeypress validation, one directive is to validate only numerics and the other directive validate only letters [A-Z].
<input type="text" id="txt_siaf" class="form-control" ng-model="siaf" maxlength="10" valid-numeric />
Given that my input text currently assigns a valid-numeric directive, I need to know how to change it by the valid-letters directive.
I would appreciate your support.
**You change the value of variable $scope.showNumericDirective dynamically.**
Add in template
<input type="text" ng-if="showNumericDirective" id="txt_siaf" class="form-control" ng-model="siaf" valid-numeric />
<input type="text" ng-if="!showNumericDirective" id="txt_siaf" class="form-control" ng-model="siaf" valid-letters />
var myapp = angular.module("myapp", []);
myapp.controller('controllerName', function($scope)
{
$scope.showNumericDirective = true;
});
myapp.directive('validNumeric', function() {
});
myapp.directive('validLetters', function() {
});
Well i don't think so that you can add or remove directive dynamically from input but you can play with other work around like:
in controller:
$scope.validNumericDirective = true;
and in template:
<input type="text" id="txt_siaf" ng-if="validNumericDirective" class="form-control" ng-model="siaf" maxlength="10" valid-numeric />
<input type="text" id="txt_siaf" ng-if="!validNumericDirective" class="form-control" ng-model="siaf" maxlength="10" valid-letters />
this logic will do the trick but you have to toggle validNumericDirective in your controller on any event.
Update:
There is a way where you can add or remove directive dynamically but it has a lengthy process see:
Angularjs dynamically adding and removing elements using directive
https://www.codeproject.com/Tips/1038684/AngularJs-Add-Remove-Directives-Dynamically-Save-D
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
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" />
<form name="{{ formname }}" novalidate>
<input type="text" ng-model="first_name" required>
<input type="text" ng-model="last_name" required>
<input type="text" ng-model="email" required>
<span class="error" ng-show="formname.$invalid">Fill in required fields.</span>
<button type="submit"></button>
</form>
I'm trying to validate the form using Angular's built in validation but because the formname is set dynamically by text passed in from the scope I'm not sure how to call it. This attempt above doesn't work.
You can do it with a little help from the controller. Define another variable (f in the example below), watch formname and update f accordingly:
.controller("...", function($scope) {
$scope.first_name = "";
$scope.formname = "fff";
$scope.f = null;
$scope.$watch("formname",function(newval,oldval,scope) {
scope.f = scope[newval];
});
});
See fiddle: http://jsfiddle.net/T7vuD/