automatically populate the value of first text box into second (angularJS) - angularjs

I need to automatically populate second textbox once the first textbox is populated by user using angularjs. Both of them have their own ng-model so I can not change ng-model. Is there a way I can just copy the value from first textbox to second by keeping ng-model different?

In the controller, you need to build the logic to assign model1 value to model2 whenever there is a change in model1
Your html part :
<input ng-model='model1" ng-change="update2()">
<input ng-model='model2" >
And somewhere in the relevant controller,
$scope.update2 = function(){
$scope.model2 = $scope.model1;
}

You can monitor changes to your $scope using the $watch function. This is a more appropriate way for binding changes in Angular. try below snippet:
Controller:
$scope.$watch('first',function(){
$scope.second = $scope.first;
});
HTML:
<input ng-model='first'>
<input ng-model='second' >

Related

Setting initial value of a select list generated through ng-repeat in angular

I am creating a select list from an associative array using ng-repeat.The ng-model of list is bound to a scope variable that has some initial value.The value of the options generated are the key of the array.
However, the list does not initialize with the value of the model.I thought it might have something to do with the asynchronous behaviour of ng-repeat, so i created a directive to capture the end of rendering and emit an event.This event is caught in the controller and is used to re-assign the value of the ng-model.
The event is caught correctly, but the update to the ng-model does not reflect.
If I attach a function to a button that updates the variable , it shows correctly in the list.
I know it is so because of the way ng-repeat works.How can i work around this automatically set the initial value after the list has been rendered.
Here is an example of my issue:
http://jsbin.com/gapemenova/1/edit?html,js,output
HTML:
<h1 align='center'>
{{value}}
<select ng-model='value' >
<option ng-repeat='(tid,groups) in templates' value='{{tid}}' on-last-repeat >{{tid}} </option>
</select>
<button ng-click='refresh()' >Refresh</button>
</body>
JS:
var app=angular.module('gobo',[]);
//Create A Directive To Detect The End Of ng-repeat cycle.
app.directive('onLastRepeat',function(){
return function(scope,element,attrs) {
if(scope.$last) { setTimeout(function(){
scope.$emit('onRepeatLast',element,attrs);
},10);
}
};
});
app.controller('goboCtrl',function($scope){
//Initial Value
$scope.value="2";
$scope.$on('onRepeatLast', function(scope, element, attrs){
$scope.value='3';
alert($scope.value); });
//Data Source For ng-repeat
$scope.templates={};
$scope.templates["1"]=[{"prop":"value1"}];
$scope.templates["2"]=[{"prop":"value2"}];
$scope.templates["3"]=[{"prop":"value3"}];
$scope.refresh=function(){
$scope.value="2";
};
}); //Controller ends
Check this working demo: JSBin
Simply change the option to:
<option ng-repeat='(tid,groups) in templates' value='{{tid}}'
ng-model="value" ng-selected="value === tid" on-last-repeat >{{tid}}</option>
Adding ng-model binds the selected value to $scope.value. Using ng-selected to update the selected item dynamically.
Explanations
Updating at the end of ng-repeat through $on is out of Angular $digest lifecycle, you need to run $scope.$apply to trigger a $digest cycle manually. Check JSBin
ngClick will trigger a $scope.$apply by default. Check ngClick definition in Angular 1.4.1 Line 23244:
scope.$apply(callback);
You should be using ng-options instead of using an ng-repeat to bind your options to your array. More on ng-options: https://docs.angularjs.org/api/ng/directive/ngOptions

Angularjs conditional binding

I have used angular's ng-model for quite some time which demonstrates two way data binding. What i want to accomplish is to bind only an input field to a model only if there are changes.
If I have
<input value="Hello world">
I want the value to be propagated to a model variable only if there are changes made to the value.
Answer would depend on event you want to use to update model.
Assuming you are wanting an "edit form " but don't want the master model to update live you can make a copy of the model and extend the master on "save"
Starting data:
$scope.item ={age: 25, name: 'Foo Bar'};
$scope.editItem = angular.copy($scope.item);
HTML
<input ng-model="editItem.age">
<button ng-click="updateItem()">Update</button>
Update function:
$scope.updateItem = function (){
$http.put(url, $scope.editItem).success(function(resp){
// merge data
angular.extend( $scope.item, $scope.editItem);
});
}
You could also do something similar using ng-change
You can do it with using of additional variable and $watch. Example:
<input type="search" ng-model="searchText">
And in controller
$scope.$watch('searchText', function() {
$scope.filterText = $scope.searchText;
});
So $scope.filterText will be changed to $scope.searchText value if any changes in input

angularjs ng-paste not updating model value

I have used ng-paste for textarea while pasting the link in textarea, i am calling a custom function to store that value. Please refer following code
<textarea rows="1" ng-model="myObj.content"
ng-paste="getContent(myObj)">
</textarea>
$scope.getContent = function(a){
console.log(a.content);
}
But in console always I am getting undefined value. How can I get my object value?
Passing model to function does not really make sense since you have already specified ng-model, so it's value will be updated as user types something into the textbox. If you want to track changes you can setup a $watch for your model or specify a function using ng-change.
If you want to know what user pasted, then that's another story. Handling ng-paste can be tricky. To access the actual event, easiest is to include jQuery before angularjs and then do e.g. following:
HTML template
<textarea rows="3"
placeholder="copy/paste here..."
ng-init="content = null"
ng-model="content"
ng-paste="paste($event.originalEvent)">
</textarea>
Controller
$scope.paste = function (event) {
var item = event.clipboardData.items[0];
item.getAsString(function (data) {
console.log(data);
});
};
Related plunker here http://plnkr.co/edit/ea5y5j
Simply use $timeout to call your paste callback after the model has been updated.
$scope.getContent = function(a){
$timeout(function () {console.log(a.content)});
}

i need an alternative solution for ng-change

i tried calling the values using ng-change between two different ng-models. it works.
but the data is parsed to the other ng-model only if the data is changed, is there any alternate solution where i can have the data in both ng-models before changing data
I tried something like this
HTML
<input ng-model="customer.name" ng-change='tripsheet.customer_name=customer.name;'>
<input ng-model="tripsheet.customer_name" type="text" class="form-control input-lg" placeholder="Customer Name">
JS
$scope.customer = {
name:$scope.customers[$scope.whichItem].name,
address:$scope.customers[$scope.whichItem].address,
phone:$scope.customers[$scope.whichItem].phone
}
i want the routeParams data in both the above ng-models.
With something like this in your controller?
$scope.customer = {
name: "Tom"
};
$scope.tripsheet = {
customer_name: $scope.customer.name
}
Plunker
#mainguy's answer is a very good approach.
Or alternatively you can go with $watch instead of ng-change.
initialize a watcher for the model object
$scope.$watch('customer.name', customerNameChanged);
and define the function
function customerNameChanged() {
if(!$scope.tripsheet)
$scope.tripsheet = {};
$scope.tripsheet.customer_name = $scope.customer.name
}
ng-change triggers only when there is a user interaction and the data is changed.
$watch is triggered when the model object is changed programmatically and also when they’re being defined the first time

AngularJS calculated ng-model

I have following controller.
app.controller("testCtrl", function(){
$scope.utcTime = 1380150771;
$scope.parseTime = function(t){
//return local time string
}
});
In the view, I have
<input type="text" ng-model="parseTime(utcTime)" />
Its not working. Can I bind ng-model to a method that returns the string ?
Any alternative way to show the value in the input button ?
You can use ngChange and ngModel both
JS
$scope.utcTime = 1380150771;
$scope.parseTime = function(){
console.log($scope.utcTime);
//return local time string
}
HTML
<input type="text" ng-change="parseTime()" ng-model="utcTime" />
ng-model is mapping through tag and controller.
At first you can see default utcTime (1380150771) that you assign in input tag.
And when you change the text in input tag, ng-model(utcTime) will be changed automatically in the controller.
Then each letter that you typed will call ng-change(parseTime) function.
You can check by console.log method.
My solution is based on this source:
https://groups.google.com/forum/#!topic/angular/1mnra0vamtg
I have edited the Plunker sample code to use ng-value to generate and update ng-model using calculation function. See this link below:
http://plnkr.co/edit/Fmqw0wp37Ndk1yuWvFkV?p=preview
Also, the above sample shows you how you format the result for display using custom filter.
In other posts, some have suggested using $watch() to detect change to input variables and update ng-model variable accordingly. Using ng-value is much better than using $watch() since the latter forces you to include all input variables in the watch which may be impossible if you have very complex calculation model.
Tarek
Try doing this
app.controller("testCtrl", function(){
$scope.utcTime = 1380150771;
$scope.result= $scope.parseTime( $scope.utcTime)
$scope.parseTime = function(t){
//return local time string
}
});
html
<input type="text" ng-model="result" />
Yes you can try follwing:
its working example:
<input type="text" ng-model="parseTime(utcTime)" />
app.controller("testCtrl", function(){
$scope.utcTime = 1380150771;
$scope.parseTime = function(t){
//return local time string
new Date(t).toISOString();
}
});

Resources