Configure Angular to re-evaluate on blur instead of keypress - angularjs

By default, it seems that Angular reevaluates its binding from a particular DOM element (e.g Text Input) to the underlying scope property on keypress or paste - i.e, whenever the value in the text input changes.
Is it possible to make it only refresh the binding on blur? I.e. do something like:
<div ng-app>
<div ng-controller="ctrl">
<input type="text" ng-model="base" ng-update-type="blur"/>
<input type="text" />
<span ng-bind="doubled()" />
</div>
</div>
Take the following JS fiddle:
http://jsfiddle.net/f76dW/
I would like the doubled span to only update when I move the focus out of the first input

You can use ng-blur and a dummy variable (base_ in this case) to achieve that effect: http://jsfiddle.net/f76dW/1/
Template
<input type="text" ng-model="base_" ng-blur="updateBase()" />
Controller
function ctrl($scope) {
$scope.base = $scope.base_ = 1000;
$scope.updateBase = function () {
$scope.base = $scope.base_;
};
$scope.doubled = function() {
return $scope.base * 2;
}
}

Use ng-model options. Using a blur hack is tricky, because a blur may not be a change.
<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options={updateOn: 'blur'}"/>

Related

ng-change triggered before value is updated

I have a form which needs to save data each time something is changed. I've used ng-change on all form elements to trigger a form validation and a save. However in case of radio buttons, ng-change is triggered before the actual value is updated, thus resulting in an invalid form on the first try, and an outdated form all subsequent times.
I've set up a JSFiddle to illustrate this. The console prints out whether the form is valid or not. The same applies if I were to print the value of $scope.form.test.$modelValue.
// HTML
<div ng-controller="MyCtrl">
<form name="form">
<input type="radio" name="test" ng-model="test" value="yes" required ng-change="checkRadios()" /> Yes<br/>
<input type="radio" name="test" ng-model="test" value="no" required ng-change="checkRadios()"/> No
</form>
</div>
// JS
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.test = null;
$scope.checkRadios = function(){
console.log($scope.form.test.$modelValue);
}
}
Is my logic faulty, is this a valid bug, or does it work as expected? In the last case, what can I do to always get the actual value?
You need a delay to get the updated value of the $scope.form, so it is possible to achieve by using $timeout
http://jsfiddle.net/loen22/w7dpx57f/
$scope.checkRadios = function(){
$timeout(function () {
console.log($scope.form.$valid);
});
}

angular.element is not working in tabset directive of angular js

I'm using tabset directive of angular js and using twitter bootstrap slider in tab,
My slidestop event is not calling but it's working well outside tab.
I know that tabset directive have its own scope , but dont know solution of following problem:-
<tabset class="tab-container">
<tab heading="tab1">
<div class="form-group">
<label>any Level</label>
<div class="input-group w-md">
<input id="slider" ui-jq="slider" ui-options="{min: 0,max: 10,step: 1,value: {{any_level}}}"
class="slider slider-horizontal form-control" type="text"
ng-model="any_level"> {{any_level}}
</div>
</div>
</tab>
</tabset>
controller code
......
angular.element("#slider").on('slideStop', function(data){
alert('asdasd');
})
problem is - alert is not coming when slider inside tab,alert is comming when slider outside tab
i am using this slider
Thanks
i have solved using ui-event directive to fire slidestop event
Html Code
<input id="slider"
ui-event="{slideStop: 'alertChange($event)'}" ui-jq="slider"
ui-options="{min: 0,max: 10,step: 1,value: {{any_level}}}"
class="slider slider-horizontal form-control" type="text" ng-model="any_level">
{{any_level}}
Controller Code
$scope.alertChange = function(data){
console.log(data.value); // i can get slider value on slidestop
}
Just don't use angular.element in an angular app.
EDIT : This isn't really working with ui-slider. Till ui-slider is work in progress i just woudn't use it.
Add this to your input :
ng-change="alertChange()"
And this to your controller :
$scope.alertChange = function(){
alert('hi');
}
What wasn't working ? In most of the case an angular.element will try to bind your even to the element too early. Your DOM "#slider" element isn't probably loaded when your try to bind.
EDIT An alternative :
First, after paying more attention i wouldn't recommend this slider at all.
This is actually a work in progress and isn't really reliable.
I made you an exemple of a html slider with binding in this plunker
You slider looks like this :
<input id="slider"
ng-model-options="{ debounce: 100 }"
min="0"
max="100"
ng-init="any_level = 0"
ng-change="alertChange()"
type="range"
ng-model="any_level">
This will update the model each time the value will not change for 100miliseconds. You need this to avoid firing too much ng-change function.
In your javascript you just need to declare your function
$scope.alertChange = function(){
console.log("I changed !");
//or anything else you want to do
}
I know this is not a solution but an alternative. It's not sexy as the other slider, but at least it works.
Hope it helped you.
The slider you are using has an example demonstrating how to do this. Take a look at box "12" on this page: http://angular-ui.github.io/ui-slider/demo/demo.html
In your controller you can add the following:
$scope.slider = {
'options': {
stop: function (event, ui) { $log.info('Slider stop'); };
}
And your HTML you must reference slider.options so your callback is fired:
<div ui-slider="slider.options"
min="0" max="50" ng-model="any_level"></div>

ng-change not working on a text input

I am new to angular js. In my code there is color picker initialized from a text field. User changes the value of color and I want that color to be reflected as a background of a text in a span. It is not working. What is missing?
HTML:
<body ng-app="">
<input type="button" value="set color" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<input type="text" name="abc" class="color" ng-change="myStyle={color:'green'}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</body>
Plunker - http://plnkr.co/edit/APrl9Y98Em0d6rxuzRDE?p=preview
However when I change it to ng-click it works.
ng-change requires ng-model,
<input type="text" name="abc" class="color" ng-model="someName" ng-change="myStyle={color:'green'}">
I've got the same issue, my model is binding from another form, I've added ng-change and ng-model and it still doesn't work:
<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>
<ng-dropzone
dropzone="dropzone"
dropzone-config="dropzoneButtonCfg"
model="pdfUrl">
</ng-dropzone>
An input #pdf-url gets data from dropzone (two ways binding), however, ng-change doesn't work in this case. $scope.$watch is a solution for me:
$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
if (newPdfUrl !== oldPdfUrl) {
// It's updated - Do something you want here.
}
});
Hope this help.
When you want to edit something in Angular you need to insert an ngModel in your html
try this in your sample:
<input type="text" name="abc" class="color" ng-model="myStyle.color">
You don't need to watch the change at all!
Maybe you can try something like this:
Using a directive
directive('watchChange', function() {
return {
scope: {
onchange: '&watchChange'
},
link: function(scope, element, attrs) {
element.on('input', function() {
scope.onchange();
});
}
};
});
http://jsfiddle.net/H2EAB/
One can also bind a function with ng-change event listener, if they need to run a bit more complex logic.
<div ng-app="myApp" ng-controller="myCtrl">
<input type='text' ng-model='name' ng-change='change()'>
<br/> <span>changed {{counter}} times </span>
</div>
...
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = 'Australia';
$scope.counter = 0;
$scope.change = function() {
$scope.counter++;
};
});
https://jsfiddle.net/as0nyre3/1/
First at all i'm seing your code and you haven't any controller. So i suggest that you use a controller.
I think you have to use a controller because your variable {{myStyle}} isn't compile because the 2 curly brace are visible and they shouldn't.
Second you have to use ng-model for your input, this directive will bind the value of the input to your variable.

Referencing the element that is calling a controller function Angularjs ( ng-change / ng-blur / ng-* ? )

The original question asked about how to determine which element called the controllers blurr function, but I didn't clarify that I was not specifically asking about ng-blur, but ng-* (ng-change, ng-focus, ng-mouseover, ng-*) in general. So, with that in mind:
How do I determine which element input is calling the blurr() and/or check() functions?
html
<body ng-app="test">
<div ng-controller="Cntrlr as cntrlr">
<form name="meta_test">
<input type="text" name='inpt' ng-model="cntrlr.inpt" ng-blur="cntrlr.blurr()" ng-change="cntrlr.check()" />
<input type="text" name='second' ng-model="cntrlr.second" ng-blur="cntrlr.blurr()" ng-change="cntrlr.check()" />
</form>
</div>
</body>
js
var app = angular.module("test", []);
app.controller("Cntrlr", ["$scope", function($scope){
this.blurr = function(){
alert("which input am I?");
alert("this is so meta.");
// ?
};
this.check = function(){
alert("this is how meta I am:");
alert(this);
}
$scope.Cntrlr = this; // see: (reference)
return $scope.Cntrlr;
}]);
You may be asking yourself "why would he want to do this?"
There are 2 reasons:
because I want to call:
$scope.user_form[meta_test.[(whatever this element is.name)]].$setValidity('spike', false);
because I'm curious. There has to be a simple way to do this.
(reference):
controller as syntax
Use this -
<input type="text" name='inpt' ng-model="cntrlr.inpt" ng-blur="cntrlr.blurr($event)" ng-change="cntrlr.check()" />
This returns the jQuery lite version of the event that causes the blurr function. Once you receive this element in your controller, you can pretty much do whatever you want with it.
The .target attribute of the event will give you the required element.
Should work
Try this:
<form name="meta_test">
<input type="text" name='inpt' ng-model="cntrlr.inpt" ng-blur="cntrlr.blurr()"
ng-change="cntrlr.check('One')" />
<input type="text" name='second' ng-model="cntrlr.second"
ng-blur="cntrlr.blurr()" ng-change="cntrlr.check('Two')" />
</form>
In JS,
this.check = function(Type){
if(Type == "One"){
//Then it is the first text box.
}else if(Type == "Two"){
//Then it is the second text box.
}
}

With AngularJS can I call a function when a user changes a value in a text field?

I have some text fields on my web page. Is there a way that I can call a function when a user changes a value in a text field without using a watch?
Yes. Check out ng-change. It allows you to run a function when an input changes.
<script>
function Controller($scope) {
$scope.counter = 0;
$scope.change = function() {
$scope.counter++;
};
}
</script>
<div ng-controller="Controller">
<input type="text" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
<label for="ng-change-example2">Confirmed</label><br />
<tt>counter = {{counter}}</tt><br/>
</div>
I don't have enough mana to make comment, so - for delaying fire action you can use ng-model-options directive and debounce
Details in documentation: https://docs.angularjs.org/api/ng/directive/ngModelOptions

Resources