How to toggle a Boolean on checkbox in Angularjs - javascript

I am working on the following code. How can I toggle the state of the Boolean, here isChecked through controller in Angularjs checkbox?
<body ng-app="app">
<div ng-controller="checkController">
<input type="checkbox" ng-model="choice" name="item" ng-change="changeSta(choice)" /> Add New Item
</div>
</body>
<script>
var app = angular.module('app', []);
app.controller('checkController', function($scope) {
var isChecked = false;
$scope.changeSta = function() {
//isChecked = true;
};
});
</script>

You can simply check for the changes in your checkbox model:
var app = angular.module('app', []);
app.controller('checkController', function($scope) {
var isChecked = false;
$scope.changeSta = function() {
console.log($scope.choice);
};

Related

Angular 1 - toggle radio button

I need to make a radio button toggle when user click. Is more then 2 buttons.
So, when I click one button if this is selected will no longer be. If is not must be selected.
I try this, but is not works:
app.directive('toggleRadio', function($timeout) {
return {
restict: 'A',
link: function(scope, el, attrs) {
var radioState;
el.on('click', function(){
if (radioState === this) {
this.checked = false;
radioState = null;
} else {
radioState = this;
}
scope.$apply();
});
}
}
It's not require to be a directive... Thanks.
Since it's a single radio button and as you said It's not required to be a directive, which doesn't seem to be necessary as well, then you can do something like below:
var app = angular.module('app', []);
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.checked = false;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl">
<input type="radio" ng-model="checked"
ng-value="true" ng-click="checked=!checked" />
{{checked}}
</div>
</div>
Updated:
Ideally, you should use checkboxes for such requirement, but if it so necessary to use radio, then do it like below:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.valChanged = false;
$scope.checked = "b";
$scope.toggle = function() {
if (!$scope.valChanged) {
$scope.checked = "";
}
$scope.valChanged = false;
}
});
<script src="https://code.angularjs.org/1.5.2/angular.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl">
<br>
<input type="radio" ng-model="checked" value="a"
ng-change="valChanged = true" ng-click="toggle()" />Option A
<br>
<input type="radio" ng-model="checked" value="b"
ng-change="valChanged = true" ng-click="toggle()" />Option B
<br>
<input type="radio" ng-model="checked" value="c"
ng-change="valChanged = true" ng-click="toggle()" />Option C
<hr> {{checked}}
</div>
</div>
I choose to create this directive:
myApp.directive('toggleRadio', [function(){
return {
restrict: 'A',
link: function(scope, el, attrs) {
el.on("mouseenter", function(e){
scope.radioStr = e.target.checked;
console.log('scope.radioStr hover: ', scope.radioStr);
});
el.on("click", function(e){
if(scope.radioStr) {
e.target.checked = false;
scope.radioStr = false;
}
else {
e.target.checked = true;
scope.radioStr = true;
}
});
}
}
}]);
And in HTML I have:
With this approach it will works just when user clicks on input itself, not for label. If somebody wants that, must rewrite this directive to find input status with, el.find(), el.next() etc.
Thanks everyone, all your informations help me to understand what've done!

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);
}
};
}]);

accessing attribute directive values using controller as

I know how to do it Without controller as:
html
Let's assume I have a directive named ngUpperCase(either true or false)
<div ng-controller="myControl" >
<input type="text" ng-upper-case="isGiant" >
</div>
Js
myApp.directive('ngUpperCase',function(){
return{
restrict:'A',
priority:0,
link:function($scope,element,attr){
//---to retrieve value
var val = $scope[attr.ngUpperCase];
var anotherVal = $scope.$eval(attr.ngUpperCase);
$scope.$watch(attr.ngUpperCase,function(val){
//---to watch
})
}
};
})
How to make the directive if I'm using something like this?
<div ng-controller="myControl as ctl" >
<input type="text" ng-upper-case="ctl.isGiant" >
</div>
Since it's not very clear what you want to achieve, here is an example of doing what I understand you need: changing an input value to upper or lower case depending on a variable:
function ngUpperCase() {
return{
restrict:'A',
priority:0,
link:function($scope,element,attr){
//---to retrieve value
var val = $scope[attr.ngUpperCase];
var anotherVal = $scope.$eval(attr.ngUpperCase);
$scope.$watch(attr.ngUpperCase,function(val){
if(val) {
element[0].value = element[0].value.toUpperCase();
} else {
element[0].value = element[0].value.toLowerCase();
}
})
}
}
}
function myController() {
this.isGiant = true;
}
angular.module('myApp', []);
angular
.module('myApp')
.controller('myController', myController)
.directive('ngUpperCase', ngUpperCase);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myController as ctl" >
lower case<br>
upper case
<input type="text" ng-upper-case="ctl.isGiant" value="TeStiNg123" >
</div>
</div>

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