set default value of input field based on another field in Angular - javascript

In Angular (1.5) I have a form with two input fields:
ID
URL
The rules:
If the ID field is empty then the URL field should be empty
If the URL field is manually set then it should not change automatically
Otherwise the URL field should be "http://myurl/"+ID+".txt"
How do I achieve this?

<input type="text" name="url"
ng-model="url"
ng-model-options="{ getterSetter: true }" />
...
function defaulUrl() {
if $scope.ID {
return 'http://myurl/'+$scope.ID+'.txt';
}
return ''
}
var _url = defaultURl();
$scope.url = {
url: function(url) {
return arguments.length ? (_url= url) : defaulUrl();
}
}
};

Use $watch on ID Field. If the ID field is changed, the watch function will be called.
$scope.$watch('$scope.ID', function() {
$scope.url = 'http://myurl/' + $scope.ID + '.txt';
}, true);

Here is a fiddle I made that meets your requirments:fiddle
The code
//HTML
<div ng-app="myApp" ng-controller="MyController">
ID <input type="text" ng-model="data.id" ng-change="onIDChange()"/>
URL <input type="text" ng-model="data.url" ng-change="onManualUrlChange()"/>
</div>
//JS
angular.module('myApp',[])
.controller('MyController', ['$scope', function($scope){
$scope.data = {
id:'',
url:''
}
$scope.manualUrl = false;
$scope.onIDChange = function(){
if(!$scope.manualUrl){
if($scope.data.id === ''){
$scope.data.url = '';
} else {
$scope.data.url = "http://myurl/" + $scope.data.id + ".txt";
}
}
}
$scope.onManualUrlChange = function(){
$scope.manualUrl = true
};
}]);

Related

Use $scope function on input type checkbox with ngClick or ngChecked to dispaly results

I want to show results on clicking checkbox items.
For that I tried with ng-click but it returns results only after it was unchecked rather on checked.
Here is my code:
HTML:
<div class="business-type">
<div class="col-sm-12 filter-wrap-inner">
<label for="rad1" ><input type="checkbox" name="reason-closing" value="Transporter" id="ad_Checkbox1" class="ads_Checkbox" ng-model="isTransporterSelected" ng-change="searchUser()"> Transporter</label>
</div>
<div class="col-sm-12 filter-wrap-inner">
<label for="rad1" ><input type="checkbox" name="reason-closing" value="Broker" id="ad_Checkbox1" class="ads_Checkbox" ng-model="isBrokerSelected" ng-change="searchUser()">Broker</label>
</div>
<div class="col-sm-12 filter-wrap-inner">
<label for="rad1" ><input type="checkbox" name="reason-closing" value="Fleet Owner" id="ad_Checkbox1" class="ads_Checkbox" ng-model="isFleetownerSelected" ng-change="searchUser()">Fleet Owner</label>
</div>
</div>
JS:
$scope.isTransporterSelected = false;
$scope.isBrokerSelected = false;
$scope.isFleetownerSelected = false
$scope.searchUser = function(){
$('.load-board-loader').show();
var i;
var containCount= 41;
var vFromStateId = vToStateId = fromStateId = toStateId = '';
var stateId=[];
var $el=$("#usersearch-origin");
$el.find('option:selected').each(function(){
stateId.push({value:$(this).val(),text:$(this).text()});
});
var originId=[];
var $el=$("#usersearch-source");
$el.find('option:selected').each(function(){
originId.push({value:$(this).val(),text:$(this).text()});
});
for(i=0;i<(stateId.length);i++)
{
if(i==0)
{
fromStateId = stateId[i].value;
}
else{
fromStateId = fromStateId+','+stateId[i].value;
}
}
for(i=0;i<(originId.length);i++)
{
if(i==0)
{
toStateId = originId[i].value;
}
else{
toStateId = toStateId+','+originId[i].value;
}
}
vFromStateId = fromStateId ;
vToStateId = toStateId ;
var data ={
fromStateIds: vFromStateId,
toStateIds: vToStateId,
typeOfBusiness: businessTypeValue,
vehicleClassIds: truckTypeValue,
orgName: '',
}
var url = 'url.com';
//if(vFromStateId != '' || vToStateId != ''){
$.ajax({
url: url,
type: "POST", //Use "PUT" for HTTP PUT methods
dataType: 'json',
data: data,
success:function(response){
if ($scope.isTransporterSelected || $scope.isBrokerSelected || $scope.isFleetownerSelected) {
debugger
$scope.users = response.directory;
for(var j= 0; j<response.directory.length; j++){
}
$scope.$apply();
$('.load-board-loader').hide();
} else {
$scope.users = response.directory;
for(var j= 0; j<response.directory.length; j++){
}
$scope.$apply();
$('.load-board-loader').hide();
}
},
error: function(error){
alert("Sorry , No data available");
}
});
I am updated my code with latest code as per comments below in this question.
Please let me know which part i need to change.
Any help over this will be very much helpful.
You should bind ngModel directive with checkbox then use ngChange which evaluates the given expression when the user changes the input value instead of ngClick
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', ['$scope', function($scope) {
$scope.isTransporterSelected = false;
$scope.searchUser = function() {
//For debugging
console.clear();
if ($scope.isTransporterSelected) {
console.log('Transporter selected search student')
} else {
console.log('Transporter deselected donot search student')
}
}
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller as nb">
<label><input type="checkbox" ng-model="isTransporterSelected" value="Transporter" ng-change="searchUser()" > Transporter</label>
</div>

Validating custom component in angular 1.5

I was working in angular project, There I had come across a situation in which I need to validate custom component having a textbox.
<dollar-text-validate ng-model="ctrl.value" required name="myDir"></dollar-text-validate>
My Component
angular.module("myApp", []);
angular.module("myApp").controller('MyController',function(){
var ctrl = this;
ctrl.value = 56;
});
angular.module("myApp").component('dollarTextValidate',{
bindings: {
ngModel :'='
},
template: '<div><input type="text" ng-focus="ctrl.focus()" ng-blur="ctrl.blur()" ng-model="ctrl.amount1"><input type="hidden" ng-model="ctrl.ngModel"></div>',
controller: function() {
var ctrl = this;
// ctrl.amount1 =
ctrl.amount1 =ctrl.ngModel===undefined||ctrl.ngModel==='' ? '' :'$'+ctrl.ngModel;
console.log(ctrl.ngModel);
ctrl.focus=function(){
ctrl.amount1 = ctrl.amount1 === undefined ? '' : ctrl.amount1.slice(1);
ctrl.ngModel = ctrl.amount1;
console.log(ctrl.ngModel);
}
ctrl.blur=function(){
ctrl.ngModel = ctrl.amount1;
ctrl.amount1 = ctrl.amount1==='' ? '' :'$'+ctrl.ngModel;
console.log(ctrl.ngModel);
}
},
controllerAs:'ctrl'
})
This component is used to set $ symbol in front of entered value. So $ appended value will be available in textbox and original value which is to be validated in hidden field.
How can I validate hidden field. I tried with required attribute in hidden tag but nothing happening. Also tried with custom tag.
Sorry to break it to you, but you might wanna go for directive, and then use $parsers, $formatter and $validators properties of ngModelController.
Component can be used for this, but it is just easier with normal directive.
angular.module('myApp', []);
angular.module("myApp").directive('dollarTextValidate', function() {
return {
require: 'ngModel',
link: function($scope, $element) {
var regexp = /^\$(\d+(\.\d+)?)$/;
var ngModel = $element.controller('ngModel');
ngModel.$formatters.push(function(value) {
return value ? '$' + value : '';
});
ngModel.$parsers.push(function(value) {
var matched = value.match(regexp);
if (matched) {
return +matched[1];
}
});
ngModel.$validators.greaterThan10 = function (modelVal, viewVal) {
var value = modelVal || viewVal;
return value > 10;
};
},
controllerAs: 'ctrl'
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<div ng-app="myApp" ng-form="form">
dollar-text-validate = <input dollar-text-validate ng-model="value" required name="myDir"><br>
number input = <input type="number" ng-model="value" required><br>
value = {{value}}<br>
errors = {{form.myDir.$error}}
</div>

Validate the input field for existing item in object array?

in my todo list i dont want user to input same todos again again...
but my problem is, when i enter something for example (test) first time and than i enter (test2) and than i enter (test) again, so its taking a value.... how to validate properly....
fiddle
https://jsfiddle.net/LaL7h6Lv/1/
html
<div ng-app="todoApp" ng-controller="mainCtrl">
<ul>
<li ng-repeat="todoItem in todoItems">{{todoItem.name}}</li>
</ul>
<form ng-submit="addItem()">
<input type="text" ng-model="newItem">
<input type="submit" name="go">
</form>
</div>
angularjs
angular.module("todoApp", [])
.controller('mainCtrl', ['$scope', function($scope){
$scope.todoItems = [{'name' : 'akshay'}];
$scope.test = false;
$scope.addItem = function(){
if($scope.newItem){
$scope.checkRepeatTodo();
if($scope.test == true){
$scope.todoItems.push({'name':$scope.newItem});
$scope.newItem = '';
}else{
alert('same todo');
$scope.test = false;
}
}else{
alert('fill the form');
}
};
$scope.checkRepeatTodo = function(){
$scope.todoItems.filter(function(item){
if($scope.newItem === item.name){
$scope.test = false;
}else{
$scope.test = true;
}
});
};
}]);
The issue is with the $scope.test value, you override the value to true when it filters down the 3rd item.
See the Working fiddle
Alternative:
Make a javascript function rather than one in $scope and call that function return if its a valid entry or not.
This eliminates the need to have $scope.test and $scope.checkRepeatTodo as they do nothing of importance.
function checkRepeatTodo() {
var valid = true;
$scope.todoItems.filter(function(item){
if($scope.newItem === item.name){
return valid = false;
}
});
return valid;
};
And use the same as:
if(checkRepeatTodo()){
$scope.todoItems.push({'name':$scope.newItem});
$scope.newItem = '';
}
else{
alert('same todo');
}
Demo here

AngularJs Custom Directive fails the text box validation

I have written a custom directive to ensure that a text box can take only integer values.
But After using the directive, my $error.required flag always stay false irrespective of whether I have a value in the text field or not.
It works fine if I use the native input type,
<input name="name" ng-model="testvalue.number" required />
but when I use the custom directive,
<number-only-input input-value="testvalue.number" input-name="name"/>
shippingForm.name.$error.required is always false and it doesn't show the error "Please enter a value" even if the field is empty
This is the code
<body ng-controller="ExampleController">
<form name="shippingForm" novalidate>
<!--<input name="name" ng-model="testvalue.number" required />-->
<number-only-input input-value="testvalue.number" input-name="name"/>
<span class="error" ng-show="shippingForm.name.$error.required">
Please enter a value
</span>
</form>
</body>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.testvalue = {number: 1, validity: true}
}])
.directive('numberOnlyInput', function () {
return {
restrict: 'EA',
template: '<input name="{{inputName}}" ng-model="inputValue" required />',
scope: {
inputValue: '=',
inputName: '='
},
link: function (scope) {
scope.$watch('inputValue', function(newValue,oldValue) {
if (newValue == undefined || newValue == null || newValue == "") {
return;
}
if (isNaN(newValue))
{
scope.inputValue = oldValue;
return;
}
});
}
};
});
</script>
Please guide
Sunil
You code has some flaws, but i think this is because you made the example incorrect, the main issue may be here:
inputName: '=' should be replaced with inputName: '#' to hold the string value of the input name
I'm not quite sure what's wrong with your example, it just doesn't work... Anyway here's a workaround which you can use to implement your functionality.
HTML:
<div ng-app="TextboxExample" ng-controller="ExampleController">
<form name="shippingForm" novalidate>
<input number-only-input type="text" name="name" ng-model="testvalue.number" required />
<!-- <number-only-input input-value="testvalue.number" input-name="name"/> -->
<span class="error" ng-show="shippingForm.name.$error.required">
Please enter a value
</span>
</form>
</div>
Controller:
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.testvalue = {number: 1, validity: true};
}])
.directive('numberOnlyInput', function () {
return {
link: function (scope, element, attrs) {
var watchMe = attrs["ngModel"];
scope.$watch(watchMe, function(newValue,oldValue) {
if(newValue == undefined || newValue == null || newValue == ""){
return;
} else if (isNaN(newValue)) {
var myVal = watchMe.split(".");
switch (myVal.length) {
case 1:
scope[myVal[0]] = oldValue;
break;
case 2:
scope[myVal[0]][myVal[1]] = oldValue;
}
}
});
}
};
});

Ionic angularjs change returned null of $scope value?

My html
<input ng-model="query" ng-change="change(text)" type="text" placeholder="Search">
My js
$scope.query = null;
$scope.change = function() {
console.log($scope.query); // null?
$timeout(function() {
$http.get('example.com/' + $scope.query
).then(function(result){
$scope.tracks = result.data.items;
});
}, 1000);
}
Why is my $scope.query always got null within the change function?

Categories