Angular : Put in ng-model a value set in scope - angularjs

In the ng-model, i want to set a default value defined in my scope but the value is not recognized.
Here's my controller :
$scope.defaultRole = "Admin";
My view :
<input type="text"
class="form-control" ng-model="user.role='{{defaultRole}}'">
but i have {{defaultRole}} instead of Admin in my input text. Maybe it's a problem of formating but i dont know how to make it work.
Note : i can put ng-model="user.role='Admin'" directly, but i want it from the scope.
Thank you for your help !

You don't understand how ngModel works. ngModel expects an assignable angular expression. The expression is bound two way. That means that
to populate the input field, angular evaluates the expression
when the value entered in the input field changes, the variable that the ngModel expression refers to is set to the entered value
So, all you need is
<input type="text" class="form-control" ng-model="defaultRole">
That will read the defaultRole variable and populate the field with its value, and vice versa.
If you want, instead, to populate user.role with the entered value, and the field to have the defaultRole value by default, then it should be
<input type="text" class="form-control" ng-model="user.role">
and the controller should do
$scope.user.role = $scope.defaultRole;
or, if user doesn't exist yet
$scope.user = {
role: $scope.defaultRole
};
to initialize user.role to its default value.

You can do that by using ng-init. ng-model isn't suppose to deal with affectation. This will be done directly by angular.
<input type="text" class="form-control" ng-model="user.role" ng-init="user.role = defaultRole">
Working Fiddle

Related

How to set a default value through ng-init or data-ng-init?

We have an address form and would like to set a default value of x to the input phone.
<div
class="form-group ms-mb-xs"
data-ng-if="field.settings.display_type=='phone'"
>
<label>
{{field.label|msTranslate}}
</label>
<input
type="tel"
id="phone"
class="form-control"
data-ng-model="fields[field.name]"
data-ng-intl-tel-input
data-ng-init="fields[phone]=12345678"
/>
</div>
I have used data-ng-init and ng-init and tried putting a default value but it doesn't show on the front-end. Also tried value="12345678" but didn't work. Have also put the numbers in single quotes but still didn't work.
Thanks in advance.
There are two ways you can do this.
Initialize your model variable with the value you need to show.
Use ng-init to execute code so that your model variable will be given a value.
It looks that you have tried the second option data-ng-init="fields[phone]=12345678"
The only reason why the option 2 doesn't work is that the controller updates the fields[field.name] with a blank value.
So, make sure you give a default value to the model variable if the intended value is blank. Something like this:
fields[field.name] = fromDB || 'a default value'

Empty ng-model overwrites ng-value

when I use ng-model together ng-value. ng-value returns empty even there is a value given.
for example, there are two controllers called FirstCtrl and SecondCtrl.
This is FirstCtrl, and If I type a value for this input, it will write in my SeconCtrl input since I call ng-value="firstname" in my SecondController:
I can pass the value from firstctrl to secondctrl(I mean first input field to second input field). But the second input field has an ng-model called d_firstname, which doesn't allow to save ng-value but ng-value is displaying the correct value but saves empty because of ng-model(d_firstname). However, i need d_firstname if user wants to enter new value. Moreover, If I type over the input field in the secondCtrl, I can save the record because of d_firstname but if I keep not modifying anything in that input field, returns empty. hope you get the problem. Please someone help on this.. I wanted to pass data from one form to other if checkbox clicked for billing details and shopping details are same
FirstController input:
<input type="text" name="firstname" ng-model="firstname" required>
SecondCtrl input:
<input name="firstname" ng-value="firstname" ng-model="d_firstname">
There is no point in using ng-value and ng-model together.
You could use ng-change event to update the second one
<input name="firstname" ng-model="firstname" ng-change="updateName()" required>
<input name="d_firstname" ng-model="d_firstname">
Controller:
$scope.updateName = function(){
$scope.d_firstname = $scope.firstname
}
Note that you should always use an object in ng-model. You will run into problems with child scopes if you don't

AngularJS Form Validation - Bind input to model eventhough there is input error

I have a form using the built in angularjs form validation and ng-messages. Look at this code.
<div class="form-group" ng-class="{ 'has-error': form1.firstName.$invalid && form1.firstName.$touched }">
<label class="control-label">* First Name</label>
<input name="firstName" ng-model="applicant.firstName" required ng-pattern="alpha" ng-minlength="2" ng-maxlength="30" type="text" class="form-control" />
<div class="help-block has-error" ng-messages="form1.firstName.$error" ng-if="form1.firstName.$touched">
<div ng-messages-include src="/worktrustedV2/app/modules/core/templates/errorMessages.template.html"></div>
<div ng-message="pattern" class="error" style="color:red">This field requires letters only</div>
</div>
If the input doesnt trigger an error, then if you console.log($scope.applicant.firstName);, it prints the value, but if the input has an error, console.log($scope.applicant.firstName); becomes undefined.
Is there a way to make angular(or maybe it because of ng-messages) bind the input's value even if it has error? I want to make console.log($scope.applicant.firstname); to print the value even if the input has error.
EDIT: After you rephrased the question
I remember I was facing the same problem when writing an application; when you have 10000+ lines of code, you can imagine the situation. Now, if I understand it clearly, you WANT applicant.firstName to have SOME value even if the validation fails? If that's the case, let me explain to you how Angular works.
Whenever you define a field as an ng-model, the internals of Angular manage two values for this field:
$modelValue
$viewValue
As you might have guessed from the names of these variables, $modelValue is the value of the input instance to be used by the model, and the $viewValue is used for displaying it, etc. (AngularJS ngModel)
Our good friends at Angular have done something pretty useful: whenever the input field doesn't pass the test, the $modelValue is set to undefined. So, when you try to get the value of that model, Angular sees that it's empty and so returns an undefined. Also, when the validation fails, <parentForm>.$invalid is switched to true.
For your case, you can give it a default value; so, even if the validation fails, you'll get SOME value.
Simple add:
$scope.applicant.firstName = "example#gmail.com";
in the controller to get a value even after the validation fails.
Yeah! You can check if the value if undefined and break out of the function. That's the best method.
...
$scope.submit = function() {
if( $scope.firstName === undefined ||
$scope.firstName === null ) { return; }
... // Continue normal execution
}

ng-maxlength not working for a variable

I'm trying to use ng-maxLength directive to give a variable max-length for my inputs.
function ValidatorCtrl($scope, $timeout) {
$scope.name = "Star";
$scope.$metadata={};
$scope.$metadata.isRequired = true;
$scope.$metadata.maxLength=5;
}
<input type="text" ng-model="name" ng-maxlength="$metadata.maxLength"
ng-required="$metadata.isRequired" name="name" />
But it doesn't seems to be working as expected. When it is applied the model binding for the same variable is not working. Here is my plunker
If I remove ng-maxLength ng-required is going to work as expected , otherwise ng-required is also not working.
ng-maxlength does not take scope values.
Traditionally ng-maxlength is used as such ng-maxlength="3".
You can either add curly braces around your scope value or create a directive that binds scope value inside ng-maxlength.

How to get the hidden input's value by using angularjs?

In angularjs,I want to get the value of the hidden input. such as the following:
<pre>
<input type="hidden" name="captId" value="AqXpRshs9QHfxUbOWqMT" ng-model="captId">
</pre>
How to get the "hidden input" value "AqXpRshs9QHfxUbOWqMT" by using angularjs,not ajax or jquery.
You can use ng-init to initialize the value so it binds that to your model variable upon creation.
<input type="hidden" name="captId" ng-init="captId='AqXpRshs9QHfxUbOWqMT'" ng-model="captId">
Or you can get it directly if all else fails:
angular.element(document.getElementsByName('captId')[0]).val();
// or dont use angular at all
document.getElementsByName('captId')[0].value
Documentation for angular.element
By ID
document.getElementById('yourId').value
By Name
document.getElementsByName('yourName')[0].value
Keep it simple :)

Resources