AngularJs: Copy the data using ng-value but model does not update - angularjs

I'm having an issue on updating or assigning the value or data into the model using ng-value.
I would like to copy any values in the DisplayName model to CopyDisplayName and using below directives i was able to do that, But the problem is the model CopyDisplayName doesn't have any value when I submit my changes. It can only have if I inputted it manually.
<input type="Text" ng-model="DisplayName" ng-disabled="true" />
<input type="Text" ng-model="CopyDisplayName" ng-value="DisplayName" />
Forgot to include that the DisplayName is disabled.. the data will came from service call.

ngValue
Binds the given expression to the value of or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.
You can take a look in this documentation.
So basically, the one you're doing right now will not work.
You can do this in your angular controller:
$scope.copyValue = function () {
$scope.copyDisplayName = $scope.displayName;
}
In html:
<input type="text" ng-model="displayName" ng-change="copyValue()" />

Just assign one variable to another:
// in the controller
$scope.CopyDisplayName = $scope.DisplayName;
If you need to keep them in sync (and for some reason, you don't want to just use the same variable), then you can keep them updated via ng-change:
<input type="Text" ng-model="DisplayName" ng-change="CopyDisplayName = DisplayName" />
Directives like ng-value (or ng-checked) only toggle the attributes in the DOM - they do not alter the View Model.

You can add $watch on DisplayName as:
$scope.$watch('DisplayName',function(newValue, oldValue){
console.log(newValue +":"+oldValue)
$scope.CopyDisplayName = newValue;
});

To have copy updated you need copy value by reference. For that you need to wrap displayName to object:
$scope.model = {DisplayName: 'val'}; and make a copy of it: $scope.modelCopy = $scope.model;
<input type="Text" ng-model="model.DisplayName" ng-disabled="true" />
<input type="Text" ng-model="modelCopy.DisplayName" ng-value="DisplayName" />
JSFiddle

what you can do in controller is watch the model and copy that value whenever it is changed($watch will do that for you) you dont need ngChange on the HTML.
$scope.$watch('displayName', function() {
$scope.copyDisplayName = $scope.displayName;
});

Related

Angularjs: How to get value of input without ng-model

I need to make some inputs by ng-repeat, and in my json file I have in object where is a property called name, like this:
"url":"find_company",
"values":[
{
"name":"company name",
"type":"input_search"
},{
"name":"company_phone",
"type":"input_search"
}
]
I want to make search in DB, in search you can find by any field or by two or more field. Field called the same as property of object. So by ng-keyup I need to send to my function
search(field, value)
two arguments. I want to do something like this
<div ng-repeat="value in param.values">
<input ng-if="value.type == 'input_search'"
ng-keyup="search(value.name, this.text)"
type="text">
How can a send to function text of this input without using ng-model? Where this.text is value of input.
since you are using ng-keyup, you can retrieve input value with $event.target.value.
comment: this is fit for normal event like onclick, but not fit for angular.
refer the below example.
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.showValue = function(val) {
alert(val);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<input type="test" ng-keyup="showValue($event.target.value)">
</div>
This is how you do it with ngModel:
<div ng-repeat="value in param.values">
<input ng-if="value.type == 'input_search'" ng-model="value.val" ng-keyup="search(value)" type="text">
And in your controller:
$scope.search = function( item ) {
console.log( item.val ); // Here you have the value using ngModel
console.log( item.name ); // Here you have the "name" property of the element inside the loop
}
As you can see, you CAN use ngModel and by passing the object itself to the function you can access its properties from the function in the controller.
Note that there's that this.text in the view - I don't know what it is exactly so I dropped it from the example to make things clearer, but you can use it in your code of course.
I know the question said without using ng-model. But I suspect you may want this because you want to customize when data-binding occurs. If that's the case, you can use ng-model-options with ng-change:
<input type="text" ng-model="yourModel" ng-model-options="{ updateOn: 'keyup' }" ng-change="search()" />
ng-change fires when the model has been updated, which is after keyup in this case. So the value of yourModel will be up to date when search() executes.

How to use more than two ng-model in one input field

Is it possible to have more than one ng-model on one input field ?
e.g:
<input ng-model="formData.glCode" ng-model="accNumber" ng-change="accNumber = editAccountNumber(accNumber)"/>
Because all inputs where I want to apply this have ng-model set already and I also need to edit model name ng-model="accNumber"
If you can't edit the input and you are trying to bind the model to the controller use the same model which already exist on the input:
<input ng-model="formData.glCode" ng-change="formData.glCode = editAccountNumber(formData.glCode)"/>
Possible duplicate:
How to bind 2 models to one input field in Angular?
No, ngModel wasn't supposed to do things like this, at this point it is better to start relocating the logic from the view. For this scenario you could make use of $watch and get the accNumber value in controller.
Working demo :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
$scope.$watch('formData.glCode', function(){
console.log($scope.accNumber);
});
$scope.editAccountNumber = function(glCode) {
return glCode;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text"
ng-model="formData.glCode"
ng-change="accNumber = editAccountNumber(formData.glCode)"/>
</div>
You can use this code: ng-model-options
<input ng-model="name" ng-model-options="{updateOn: 'blur'}">
for more detail you can try this link:
http://www.w3schools.com/angular/ng_ng-model-options.asp

Get "raw" value from invalid input field

I have an input field in a form with some validations. It works like a charm.
It basically looks like this:
<input
class="form-control"
type="number"
ng-model="zipcode"
ng-minlength="5"
ng-maxlength="5"
id="zipcode"
name="zipcode"
required
>
A working plunkr is here: http://plnkr.co/edit/H0h59kG75T5MGE9cAhSo?p=preview
But now I also want to react to every input change - whether valid or not. So for example if the input field contains "123" it is not valid and the value is not transferred to my model - thats fine. But I still want to get the value to do some intermediate requests to a webservice.
Any Ideas?
First call the form element in your controller, then use the $viewValue attribute :
View :
<form name="form">
<input
...
ng-model="zipcode"
ng-change="getRawValue(form)"
name="zipcode"
required
>
</form>
Controller:
$scope.getRawValue = function(form) {
var rawValue = form.zipcode.$viewValue;
}
Angular 1.3 introduced a real answer for this: allowInvalid in ngModelOptions.
Example:
<input
type="text"
name="userName"
ng-model="user.name"
ng-model-options="{allowInvalid: true}"
>
Here is what i came up with for your scenario.
Basically you can write a directive which requires ngModel (ngModelController). The ngModelController has a array of parsers which it call to parse the view value in a pipeline manner. If validation fail these parsers do not update the model. If you inject a custom parser at the start of this parsers array, you can get the each view change value and do anything you want with it.
See my plunkr here http://plnkr.co/edit/ruB42xHWj7dBxe885OGy?p=preview (See console)
The basic code would be
ngModelCtrl.$parsers.splice(0,0,(function (viewValue) {
console.log("The view value is:"+viewValue)
return viewValue;
}));
Also see ngModelController documenation

Model not updated when view changes

I have a form for creating new records in a partial which I load in my main view like this
<div ng-controller="NewProductController">
<ng-include src=" 'views/partials/product-form.html' "></ng-include>
</div>
In the form, I have some input fields
..
<input ng-model="cip" type="text" id="cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>
<input ng-model="name" type="text" id="name" class="form-control" placeholder="Enter the name" />
And in my controller, I'm sending a POST request with the values of the input fields:
...
.controller('NewProductController', function(Product, $scope) {
$scope.create = function () {
Product.create( {'cip': $scope.cip,
'name': $scope.name,
'dosage': $scope.dosage,
...
});
};
The problem is that when the values of the input fields change, it is not reflected in the controller ($scope.cip and $scope.name are undefined unless I initialized them with some value) but when $scope.cip and $scope.name are changed in the controller, the changes are correctly reflected in the view.
I thought that kind of updates are automatic or am I missing something ?
The reason why this is happening because ng-include creates a child scope. Since you are managing the model fields in the child scope i.e inside the template html, the fields are not available on the parent scope, where your controller is defined.
To fix this issue first and foremost thing that you need to do would be to create a obj such as product and define it on the controller NewProductController scope.
$scope.product={};
The template then should bind to sub properties of this product object.
<input ng-model="product.cip" type="text" id="cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>
Now your changes would be available in the parent product object.
You can improve it a bit by passing the product object using ng-init like this
<ng-include src=" 'views/partials/product-form.html' " ng-init='model=product'></ng-include>
Now your template input fields change to
<input ng-model="cip" type="text" id="model.cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>
Advantage
You template is not dependent on the structure of parent model class. Dependency is explicit. The template becomes more reusable as it clearly defines the model it works with, like in your case the template works with Product model.
For the sake of completeness of the answer i must link to this must read article, Understanding Scopes

How to bind 2 models to one input field in Angular?

Is there anyway that I can bind two model values to one input field?
Suppose I have input field which I want to be the value of two variables in the scope something like:
<input type="text" model="sn_number; id" >
You cannot, but there are some workarounds.
1. Use ngChange to update the other model
<input type="text"
ng-model="sn_number"
ng-change="id=sn_number"/>
2. You could watch a model, and when in changes, update another
$scope.$watch('sn_number', function(v){
$scope.id = v;
});
You would need to watch also for changes in id if you want to keep them in sync.
Example here
You can bind fields immediately, not only in ng-change, and actually it isn't data binding, its only angular expression
<label>Name</label>
<input type="text" ng-model="name" value="{{name}}"/>
<label>Key</label>
<input type="text" ng-model="key" value="{{key=name}}" />
It would make no sense to bind an input to two variables in the model. Binding works both ways, so if the model is updated, the field is updated and vice-versa. If you were to bind to two variables, what would be the single source of truth?
However you can use ng-change to call a method on the controller which can set two variables when the field changes.
with ng-init
<div ng-controller="ctrl" ng-init="model = { year: '2013', month:'09'}">
or
<div ng-repeat="c in contact" ng-init="likes = { food: 'steak', drink:'coke'}">

Resources