how to change value based on user input, in angular? - javascript

I am trying to change the output value based on the user input, using angular. I can increment the value, however, when an input changes, the outputed value doesn't change
Here is my code:
<input type="text" ng-change="myFunc()" ng-model="myValue" />
<p>You have {{total}} points left.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.myValue = 0;
$scope.total = 5;
$scope.myFunc = function() {
$scope.total -= $scope.myValue;
};
}]);
</script>
I want it that when the user, clicks, for instance, backspace, the total goes back to its initial value (which in this example, is 5)
any ideas?

I think it is simplier to do
<input type="text" ng-model="myValue" />
<p>You have {{total - myValue}} points left.</p>
<button type="button" ng-click="myFunc()">
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.myValue = 0;
$scope.total = 5;
$scope.myFunc = function() {
$scope.total-=$scope.myValue;
};
}]);
</script>
Like this, user can see the value but apply it only with an explicit action

If you want to get back to the initial value, you can check the input length.
$scope.myFunc = function() {
if(!$scope.myValue.length){
$scope.total = 5;
}
$scope.total-=$scope.myValue;
}
http://jsfiddle.net/ugmv5od1/

I think in your change function you should have this. Add a scope.initial as the starting value rather than total, so you can go back to it when nothing is in the box.
$scope.initial=5;
$scope.myValue=0;
$scope.total = $scope.initial;
$scope.myFunc = function(){
$scope.total = $scope.initial - myValue;
}

Related

How to pass data from input to a custom service?

I am new to AngularJS and I have a problem: how to display the hex equivalent of the number inserted into the input box?
I am using ng-change to see if the input is modified and the output should also change according to the input.
This is the code:
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" ng-model="in" ng-change="hex(in)">
{{in}} <br>{{hex}}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.in= 11;
$scope.hex = hexafy.myFunc($scope.in);
});
</script>
Why it does not work?
In your input, you try to call a function:
<input type="number" ng-model="in" ng-change="hex(in)">
But $scope.hex is not a function in your controller:
$scope.hex = hexafy.myFunc($scope.in);
How to fix it?
Change it to:
$scope.hex = function() {
$scope.result = hexafy.myFunc($scope.in);
}
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.in= 11;
$scope.hex = function() {
$scope.result = hexafy.myFunc($scope.in);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" ng-model="in" ng-change="hex()">
{{in}} <br>{{result}}
</div>
Created Plunker. Problem is that you are using function name as assignment.
<input type="number" ng-model="in" ng-change="convertToHex(in)">
$scope.convertToHex= function(value) {
$scope.hex = hexafy.myFunc(value);
}

How to bind a value from one ng-model to an other by matching a specific string

I got a requirement to bind a value to a particular model when the value in the other model contains a string starting with "https".
For example, I have two text fields both fields having different model
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
Suppose I type a value on the first text field "https", the first input model modelText1 have to bind to the second input model modelText2 and later on i have to maintain it as like two-way binding. i.e. the second field will automatically get the value dynamically when it contains "https" at starting of a string.
Try it like in this Demo fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.$watch('modelText1', function (newValue) {
if (newValue.toLowerCase().match(regEx)) {
$scope.modelText2 = newValue;
} else {
$scope.modelText2 = '';
}
});
});
An other approach is (that avoid using of $watch) is to use AngularJS ng-change like in this
example fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" ng-change="change()">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.change = function () {
if ($scope.modelText1.toLowerCase().match(regEx)) {
$scope.modelText2 = $scope.modelText1;
} else {
$scope.modelText2 = '';
}
};
});
You can use the ng-change directive like this:
<input type="text" ng-model="modelText1" ng-change="onChange()">
<input type="text" ng-model="modelText2">
and your controller:
$scope.onChange = function() {
if ($scope.modelText1 === 'https') {
$scope.modelText2 = $scope.modelText1;
else
$scope.modelText2 = '';
};
use ng-change to check the text is equal to 'https'
angular.module('app',[])
.controller('ctrl',function($scope){
$scope.changeItem = function(item){
$scope.modelText2 = "";
if(item.toLowerCase() === "https"){
$scope.modelText2 = item
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="modelText1" ng-change="changeItem(modelText1)">
<input type="text" ng-model="modelText2">
</div>
EDiTED
to make sure it does't fail under 'HTTPS' use toLoweCase function to make all lower case
HTML :
<input type="text" ng-model="modelText1" ng-change="updateModal(modelText1)">
JS :
var modelText1 = $scope.modelText1.toLowerCase();
$scope.updateModal = function(){
$scope.modelText2 = '';
if(modelText1.indexOf('https')!=-1){
$scope.modelText2 = modelText1;
}
}
you could also possibly do this as a directive if you want to have a more reusable solution over multiple views http://jsfiddle.net/j5ga8vhk/7/
It also keeps the controller more clean, i always try to use the controller only for controlling complex business logic and business data
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" >
<input type="text" ng-model="modelText2" model-listener="modelText1" model-listener-value="https" >
</div>
Angular JS
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
});
myApp.directive('modelListener', [function() {
return {
restrict: 'A',
controller: ['$scope', function($scope) {
}],
link: function($scope, iElement, iAttrs, ctrl) {
$scope.$watch(iAttrs.modelListener, function() {
if($scope[iAttrs.modelListener] === iAttrs.modelListenerValue ) {
$scope[iAttrs.ngModel] = $scope[iAttrs.modelListener];
} else {
$scope[iAttrs.ngModel] = "";
}
}, true);
}
};
}]);

Service Function Not Being Triggered

I have a controller which works fine toggling hide and show on a div element at this stage I am trying to clean up so I started using a service.
Controller Snippet with toggle method inside
app.controller('addFormCtrl', function($scope, $http, $timeout, Service){
$scope.myVar = true
$scope.toggle = function (){
$scope.myVar = !$scope.myVar
//once toggled i.e form taken away success or failure message displayed for x time
$scope.successOrFailureAlert = true;
$timeout(function () {$scope.successOrFailureAlert = false}, 2000)
}
})
Service
app.service('Service', function($timeout){
var user = ""
var location = ""
this.toggle = function(var1,var2){
console.log(var1)
console.log(var2)
var1 = !var1
var2 = true;
$timeout(function () {var2 = false}, 2000)
}
})
Controller with service added
app.controller('addFormCtrl', function($scope, $http, $timeout, Service){
$scope.myVar = true
$scope.toggle = Service.toggle($scope.myVar, $scope.successOrFailureAlert)
//function (){
// $scope.myVar = !$scope.myVar
// once toggled i.e form taken away success or failure message displayed for x time
// $scope.successOrFailureAlert = true;
// $timeout(function () {$scope.successOrFailureAlert = false}, 2000)
//}
})
When I use the service instead of defining the method there. nothing happens the toggle dosen't fire. I wish I had more to add in regards to contextual information
HTML
<div ng-controller="addFormCtrl">
<span ng-show="successOrFailureAlert"> {{status}} </span>
<button ng-click="toggle()"> Add Employee </button>
<form ng-hide="myVar" ng-submit="submitAddEmployeeForm()">
<input type="text" ng-model="name">
<input type="text" ng-model="country">
<input type="submit" value="Submit" />
</form>
</div>
Call it inside a function, because your ng-click expects a function.
$scope.toggle = function(){
Service.toggle($scope.myVar, $scope.successOrFailureAlert);
}

Angular ng-model values not registered on submit

I know the title is kind of ambiguous but here is the issue: I have 2 input fields in a form that look like this:
<form name="modifyApp" class="form-signin" ng-submit="modify(val)">
<input type="text" class="form-control" ng-model="val.name" id="appName">
<input type="number" class="form-control" ng-model="val.number" id="number" min="0" max="65535">
<button type="submit">Submit</button>
</form>
When I load the page I populate those two with some values from inside the controller:
angular.module('myApp').controller('modifyAppController', ['$scope', function($scope) {
function setFields(appName, appNumber){
document.getElementById("appName").value = appName
document.getElementById("number").value = appNumber
}
$scope.modify= function(val){
console.log(val)
}
}])
The problem is when I press the Submit button. The values won't get registered unless I change them. For example, if I press the Submit button nothing gets printed, but if I change the number or the name, it gets printed.
In your controller you can simply initialize the val object like this:
angular.module('myApp', [])
.controller('modifyAppController', ['$scope', function($scope) {
$scope.val = {
name: '',
number: 0
};
function setFields(appName, appNumber) {
$scope.val.name = appName;
$scope.val.number = appNumber;
}
$scope.modify = function(val) {
console.log(val);
};
}]);
You need to rewrite your controller:
angular.module('myApp').controller('modifyAppController', ['$scope', function($scope) {
$scope.val = {
name = 'My app name',
number = '1'
};
function setFields(appName, appNumber){
$scope.val.name = appName;
$scope.val.number = appNumber;
}
$scope.modify= function(){
console.log($scope.val);
}
}])
You don't need to directly modify the DOM values in Angular. All your $scope variables are available in your template.
why not just have the following as the first line in your form
<form name="modifyApp" class="form-signin" ng-submit="modify()">
and then your controller can look like this
$scope.val = {
name: '',
number:0//some default values
}
$scope.modify= function(){
console.log($scope.val)
}

Function in AngularJs

I want to do a validation. I want exact this validation but in angularJS I am new to AngularJS and I am trying to write a function which uses if else loop. But i don't know how to write a function. Here which i have tried till now. How to call a function in html page? please anyone can help me with this.
var app = angular.module("MyApp", ["ngAnimate","ngMessages"]);
app.controller('MyCtrl', function($scope, $timeout) {
$scope.name = '';
$scope.validate = function(NetProfit) {
if (NetProfit < 500 || NetProfit > 800) {
$scope.greeting = 'Your payment must be between £500 and £800';
}
else {
$scope.greeting = '';
}
};
});
html code
<input ng-model="name2" name="name2" id="NetProfit" type="text">
{{greeting}}
You can write
<input ng-model="name2" name="name2" id="name2id" type="text" ng-change='validate(name2)'>
{{greeting}}
ngChange documentation is here
But the best way of doing this is to use $validators of ngModelController
ngModelController documentation here
Use ng-change directive which will invoke handler(expression) every time value is changed..
Try this:
var app = angular.module("MyApp", []);
app.controller('MyCtrl', function($scope, $timeout) {
$scope.name = '';
$scope.validate = function(NetProfit) {
if (NetProfit < 500 || NetProfit > 800) {
$scope.greeting = 'Your payment must be between £500 and £800';
} else {
$scope.greeting = '';
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='MyApp' ng-controller='MyCtrl'>
<input ng-model="name2" name="name2" id="NetProfit" type="text" ng-change='validate(name2)'>{{greeting}}
</div>
Fiddle here

Categories

Resources