I have mentioned my HTML.
<div ng-controller="myCtrl">
<input type=text ng-model="name">
</div>
in my JS file
function myCtrl($scope){
$scope.name=//this field comes from DB say 'ABC'
}
My question :
When my html is get loaded, it will disply "ABC" in textbox. Which is fine.
Now if user change that name to "XYZ", So $scope.name value is "XYZ".
So I need to identify that input value is changed. Previous value is "ABC" and now the value is "XYZ" how we can figured it out that value is changed?
You can use the ngChange directive.
<input type="text" ng-model="name" ng-change="change()">
Then, in your controller, add a method called change to the scope:
$scope.change = function () {
console.debug('Changed to ' + $scope.name);
}
Do it like this:
function myCtrl($scope){
$scope.$watch('name', function(newValue, oldValue){
});
}
function myCtrl($scope){
var dbName= 'ABC'; //this field comes from DB say 'ABC'
$scope.name= dbName;
$scope.$watch('name', function(newValue) {
if(newValue != dbName) {
// do something
}
});
}
Related
I want to update a text value when the value is changed by using some method, the method should not call when I am still typing text but when exit from the textbox or change it through script code:
<input type="text" ng-model ="model.value" ng-change = "update()"/>
what should contain update() method,
what I tried is : wrote a directive for this textbox, and
scope.$watch('model', function(nval,oval){
if ((oVal === undefined) && (nVal != undefined)){
update()
}
});
It is calling for the first time, but not whenever the model value changed.
I want to call update method whenever the model.value changed, but not while entering text
You can use ng-blur and you should change your $watch:
JSFiddle
HTML:
<div ng-app="myApp" ng-controller="dummy">
<input type="text" ng-model="model.value" ng-blur="update()"/>
</div>
JS:
angular.module('myApp', [])
.controller('dummy', ['$scope', function ($scope) {
$scope.model = {
value: 'hello'
};
$scope.update = function () {
console.log("changed!");
};
$scope.$watch('model.value', function (nval, oval) {
if (oval !== nval) {
$scope.update();
}
});
}]);
You can use data-ng-model-options directly to achieve your requirement.
Like,
here you can get full reference of data-ng-nmodel-options
https://docs.angularjs.org/api/ng/directive/ngModelOptions
this directive will work for the versions angular 1.4.x ( from 1.4.x version it suppports)
Let's say I have an input, like this:
<input ng-model="myinput" />
I want it to display a default value of Hello on page load/render but not touch myinput.
I can't use a placeholder since I want the user to have the ability to edit the default value of hello. Once that default value is changed by the user, then that change should be reflected in myinput.
Anyone have any ideas?
Edit: For context, these input field default values are settings that the user saved which are being displayed on an item page. If the default value is saved to the model and the item is updated, then that default value sticks. Meaning, if they change the setting, then that item won't have the new setting value. Only if the user explicitly changed the field should it save that data to the item.
If I understand you correctly, one way of doing this is like this:
$scope.myinput= '';
$scope.tempVal = "some default value";
$scope.$watch('tempVal', function(newValue, oldValue) {
if (newValue != "some default value") {
$scope.myinput= newValue;
}
});
in the html:
<input type="text" ng-model="tempVal" />
you use a temp variable for the input and only when the value is not the default change myinput
note:
Are you sure you don't want to save the default value in the variable? I find it hard to imagine a use case in which it's not the best approach. Can you describe your use case?
Initialize myinput inside of your controller:
JavaScript
app.controller('ctrl', function($scope) {
$scope.myinput = 'hello';
});
HTML
<div ng-controller='ctrl'>
<input ng-model="myinput" />
</div>
I write a directive base on how I understand the requirement , hope it can help:
https://jsfiddle.net/tm5yv4Lk/
angular.module('myApp',[])
.controller('MainController', ['$scope', function($scope) {
$scope.myinput = 'my text';
$scope.myFakeInput = 'fake text';
}])
.directive('inputMask', ['$timeout', function($timeout) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
inputMask: '='
},
link: function(scope, element, attrs, ctrl ) {
$timeout(function() {
element[0].value = scope.inputMask;
}, 0);
}
};
}]);
HTML:
<input ng-model="myinput" input-mask="myFakeInput"/>
I tried to get the HTML page value to angularJS function , The below steps are which i tried.
HTML page :
<label class="item-input item-stacked-label">
<span class="input-label cont_det_label">First Name</span>
<p class="contact_display" id="txtFirstName" ng-model="testName">Satya</p>
</label>
angularJS Page :
.controller('SocialNetworkCtrl', ['$scope','$http','$state','ContactsService','$ionicNavBarDelegate','$ionicLoading','$ionicPopup',function($scope, $http, $state, ContactsService, $ionicNavBarDelegate, $ionicLoading,$ionicPopup) {
$scope.showUserProfile = function() {
$state.go("linkedin");
var firstname = (document.getElementById("txtFirstName").value);
}
}])
So I need var firstname = Satya ?? Is it correct way please guide me to access this value .
var firstName = $scope.testName
<input ng-model="testName" />
testName is the ng-model name that you have give. It will be automatically binded to your controller. No need the get the value using document.getElementById
Wrong usage , why ng-model in <p> tag??
Update
Change your fiddle with the following code, it will work. Also make sure framework is selected properly (as in the image)
<div ng-app ng-controller="testController">
<input ng-model="testDataName" ng-change="check()" /> {{testDataName}}
After ng-change : {{checkName}}
</div>
function testController($scope) {
$scope.testDataName="Dummy Name";
$scope.check = function () {
$scope.checkName=$scope.testDataName;
console.log($scope.checkName);
};
}
its a text node, you will require .innerHTML or '.innerText', .value is for form inputs
var firstname = (document.getElementById("txtFirstName").innerHTML);
and don't use ng-model on a p element, change it to like this
<p class="contact_display" id="txtFirstName">{{testName}}</p>
just use $scope.testName to get the value, no need for firstname = (document.getElementById("txtFirstName").innerHTML); querying DOM for value is jQuery style, use angular the $scope for 2 way bindings
Read more at official doc
Update here is updated function on loginCtrl
.controller('loginCtrl', ['$scope', function ($scope) {
$scope.testNameData = 'Satya';
$scope.doLogin = function() {
alert($scope.testNameData);
};
}])
If you really want to go jQuery way here is what you can do, its not recommended, you should use angular directive to do DOM manipulation
$scope.showUserPro = function() {
$ionicLoading.show();
// Here i need the value of <p tag>
var name = document.getElementById("txtFirstName"),
firstNameFromHtmlPtag = name.innerText;
console.log(firstNameFromHtmlPtag, 'Doing API Call 1');
}
Trying to display a columnvalue from a gridcollection based on another value in that same row.
The user can select/change values in a modal which contains a grid with values. When the modal closes the values are passed back. At that moment I would like to set a value for 'Also known as':
html:
Also known as: <input type="text" `ng-model="displayValue(displayNameData[0].show,displayNameData[0].value)">`
I created a function on scope to select the value only when the 'show' value is true:
$scope.displayValue = function (show, val) {
if (show) {
return val;
}
else {
return '';
}
}
However when I close the modal I get an error:
Error: [ngModel:nonassign] Expression 'displayValue(displayNameData[0].show,displayNameData[0].value)' is non-assignable.
plnkr reference:http://plnkr.co/edit/UoQHYwAxwdvX0qx7JFVW?p=preview
Using ng-value instead of ng-model worked for me.
As HackedByChinese mentioned, you can't bind ng-model to a function, so try like this:
<input type="text" ng-if="displayNameData[0].show"
ng-model="displayNameData[0].value">
Or if you want this control to be visible you can create directive, add function to $parsers that will set empty value according to show:
angular.module('yourModule').directive('bindIf', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
function parser(value) {
var show = scope.$eval(attrs.bindIf);
return show ? value: '';
}
ngModel.$parsers.push(parser);
}
};
});
HTML:
<input type="text" bind-if="displayNameData[0].show"
ng-model="displayNameData[0].value">
You can bind ng-model to function
Binding to a getter/setter
Sometimes it's helpful to bind ngModel to a
getter/setter function. A getter/setter is a function that returns a
representation of the model when called with zero arguments, and sets
the internal state of a model when called with an argument. It's
sometimes useful to use this for models that have an internal
representation that's different from what the model exposes to the
view.
index.html
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
app.js
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
// Note that newName can be undefined for two reasons:
// 1. Because it is called as a getter and thus called with no arguments
// 2. Because the property should actually be set to undefined. This happens e.g. if the
// input is invalid
return arguments.length ? (_name = newName) : _name;
}
};
}]);
<input type="text" id="exampleab"
ng-model="a.b"
ui-event="{ blur : 'callScriptThenServer()' }" >
For some reasons the ng-change on textbox is not working so i am using it; Using Angular-ui's ui-events.
PROBLEM
I want to call the function only if the value is changed and also want the old value in callback.(since I want to send the oldValue to the server).
I don't want to go via pure directives route because there are so many occurrences of these
NG-CHANGE : on each character changed i get a callback . I don't want that. I need to call the server script .. with the old value in the text box and the new value after blur
You can watch your variable to have the newValue and oldValue at the same time.
<input type="text" id="exampleab" ng-model="a.b" >
In your controler:
app.controller('ctrl', function ($scope) {
$scope.$watch('a.b', function (newValue, oldValue) {
console.log('oldValue=' + oldValue);
console.log('newValue=' + newValue);
//do something
});
});
JSFiddle
EDIT
You mentioned a new requirement in your edit so i edit my answer.
You shouldn't use ng-change. you should get the oldValue when the control being focused and save it in a variable and then get the new value on blur event.
I set up a new fiddle.
In your controller :
app.controller('ctrl', function ($scope) {
$scope.showValues = function () {
alert('oldValue = ' + $scope.oldValue);
alert('newValue = ' + $scope.a.b);
}
});
I your view
<input type="text" id="exampleab" ng-model="a.b" ng-init="oldValue = ''" ng-focus="oldValue = a.b" ng-blur="showValues()" />{{a.b}}
Use ng-model-options
<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options="{updateOn: 'blur'}"/>
You can use AngularJS Watch
$scope.$watch(function(){
return $scope.a.b;
}, function(newvalue, oldvalue){
//Here You have both newvalue & oldvalue
alert("newvalue: " + newvalue);
alert("oldvalue: " + oldvalue);
},true);
Plunkr DEMO
Use Angular ngModelOptions with getterSetter:true; and then use method call inside the "set" part of the function.
See the last example on this page:
https://docs.angularjs.org/api/ng/directive/ngModelOptions