How to automatically select check box based on the data in angularjs? - angularjs

In my webapp there are list of check boxes present. What i need is, from back-end am getting a list where data is present, based on this data i want to automatically check the checkbox. If it confusing the below is my code.
html
<span ng-repeat="days in selectDays">
<input type="checkbox" id="{{days}}" ng-model="selectedList[days]" value="{{days | uppercase}}"/>
<label for="{{days}}">{{days}}</label>
</span>
controller
$scope.selectDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
From back end i am getting below data in response
["SUN", "MON"];
below am sharing the snapshot of my page.
My need is to check the response data with $scope.selectDays if it is present then i have to check that respective check box. i.e. if "SUN" is there in the list then i have to check that.

You can use ng-checked
<span ng-repeat="days in selectDays">
<input type="checkbox" ng-checked="response.indexOf(days) !== -1" id="{{days}}" ng-model="selectedList[days]" value="{{days | uppercase}}"/>
<label for="{{days}}">{{days}}</label>
</span>
DEMO

Look it:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div id="wrapper" ng-repeat="x in dayList">
<input type="checkbox" ng-checked="findIt(x.name)">{{x.name}}
</div>
<script>
//module declaration
var app = angular.module('myApp',[]);
//controller declaration
app.controller('myCtrl',function($scope){
$scope.dayList = [{name:'Sun'}, {name:'Mon'}, {name:'Tue'}, {name:'Wed'}, {name:'Thu'}, {name:'Fri'}, {name:'Sat'}];
$scope.marked = ['Sun','Wed'];
$scope.findIt = function(item){
if($scope.marked.indexOf(item)!= -1){return true;}
}
});
</script>
</body>
</html>
Result:
Hope, this helps!

HTML
<div ng-controller="MyCtrl">
<span ng-repeat="days in selectDays">
<input type="checkbox" id="{{days.Day}}" value="{{days.Day | uppercase}}" ng-checked="days.IsCheck"/>
<label for="{{days.Day}}">{{days.Day}}</label>
</span>
</div>
JS
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope, $filter) {
$scope.selected = ['Sun', 'Wed']
$scope.selectDays = [{"Day" : 'Sun',"IsCheck" : false},
{"Day" : 'Mon',"IsCheck" : false}, {"Day" : 'Tue',"IsCheck" : false},
{"Day" : 'Wed',"IsCheck" : false}]
angular.forEach($scope.selected,function(obj,i){
var obj = $filter('filter')($scope.selectDays, { Day: obj })[0];
if(obj != null)
{
obj.IsCheck = true;
}
})
}
Please find jsfiddle link as well
Demo

Related

angular js The ng-model name looks like 'choice.gorntu'. I want pz1, pz2 etc. to be written in ng-model part

enter image description here
The ng-model name looks like 'choice.gorntu'. I want pz1, pz2 etc. to be written in ng-model part. I did not get it. My English is not very good.
html
<div ng-repeat="choice in choices">
<input type="text" -ng-model='choice.gorntu' name="{{choice.isim}}" >
</div>
<input type="button" value='add' ng-click="addNewchoice()">
css
var benimapp =angular.module("myapp",[]);
benimapp.controller("control",function($scope){
$scope.choices = [{id: 'txt1',isim:'monday1',gorntu:'pz1'},{id:
'txt2',isim:'monday2',gorntu:'pz2'}];
$scope.addNewchoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'txt'+newItemNo ,isim:'monday'+newItemNo, gorntu:'pz'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
Try this one
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myapp" ng-controller="control">
<div ng-repeat="choice in choices">
<input type="text" ng-model='choice.gorntu' name="{{choice.isim}}" >
</div>
<input type="button" value='add' ng-click="addNewchoice()">
</div>
<script>
var benimapp =angular.module("myapp",[]);
benimapp.controller("control",function($scope){
$scope.choices = [{id: 'txt1',isim:'monday1',gorntu:'pz1'},{id:
'txt2',isim:'monday2',gorntu:'pz2'}];
$scope.addNewchoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'txt'+newItemNo ,isim:'monday'+newItemNo, gorntu:'pz'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
</script>
</body>
</html>

Angular is not allowing me do the integar comparison if value is type casted in string in controller. Please have a look at this code snippet

When i add dynamic text box and compare this value to orignal prize than the result are untrue. try to add a text box and insert 111 for instance.
<div ng-app="myApp" ng-controller="nCtrl">
<h1>{{challenge.prize}}</h1>
<a ng-click="addBoxes()"> Add Box </a>
<div ng-repeat="data in challenge.boxes track by $index">
why its not working right {{challenge.boxes[$index].prize > challenge.prize}}
<input type="text" ng-model="challenge.boxes[$index].prize">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('nCtrl', function ($scope) {
$scope.challenge = {
prize: '12',
boxes: []
};
$scope.addBoxes = function () {
$scope.challenge.boxes.push({prize: ''})
};
});
</script>
<p>The prize is written as a string, but formatted as a number.</p>
</body>
</html>
Set input type number in your html and it working fine.
Or use custom filter in place of angular number filter
app.filter('num', function() {
return function(input) {
return parseFloat(input, 10);
};
});
I have change the value of prize string to int,then getting correct output as mention below :
$scope.challenge = {
prize: 12,
boxes: []
};
see demo on fiddler link
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="nCtrl">
<h1>{{challenge.prize}}</h1>
<a ng-click="addBoxes()"> Click here to Add Box </a>
</br>
</br>
<div>
Now Its Working...
</div>
<div ng-repeat="data in challenge.boxes track by $index">
Conditional based Output :<strong> {{challenge.boxes[$index].prize > challenge.prize}} </strong>
<input type="text" ng-model="challenge.boxes[$index].prize">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('nCtrl', function($scope) {
$scope.challenge = {
prize: 12,
boxes: []
};
$scope.addBoxes = function() {
$scope.challenge.boxes.push({
prize: ''
})
console.log($scope.challenge.boxes)
};
});
</script>
<p>The prize is written as a string, but formatted as a number.</p>

AngularJS multiple checkboxes doubts (Angular Material)

I'm trying to get multiple Angular Material checkboxes with the same ng-model. I have two problems: how to get default checked checkboxes, and how to make at least one of these checkboxes to be required. I tried with ng-checked, but then I can't POST the values through the form.
HTML
<label for="inputPassword3" class="col-sm-2 control-label">Školski sat *</label>
<div class="col-sm-10" >
<span class="col-sm-2" ng-repeat="period in periods">
<md-checkbox ng-model="form.periods[period]" ng-click="toggle(period, selected)">
{{ period }}. sat
</md-checkbox>
</span>{{selected | json}}
</div>
App.js
$scope.periods = [1,2,3,4,5,6,7,8,9,0]; /*broj sati*/
$scope.selected = [2];
$scope.toggle = function (period, list) {
var idx = list.indexOf(period);
if (idx > -1) {
list.splice(idx, 1);
}
else {
list.push(period);
}
};
$scope.exists = function (period, list) {
return list.indexOf(period) > -1;
};
Please, help.
Actually your ngModel is an object, so to get selected value rendered on load, you should do the following:
$scope.model = {};
$scope.model.periods = {"2": true};
And to get all selected checkboxes you should iterate over the keys, as below:
$scope.save = function() {
// Get all checked boxes
var checked = Object.keys($scope.model.periods).filter(function(key) {
return $scope.model.periods[key];
});
console.log(checked);
}
See it working:
(function() {
angular
.module('app', ['ngMaterial'])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
$scope.model = {};
$scope.model.periods = {"2": true};
$scope.periods = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; /*broj sati*/
$scope.save = function() {
// Get all checked boxes
var checked = Object.keys($scope.model.periods).filter(function(key) {
return $scope.model.periods[key];
});
console.log(checked);
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-aria.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-animate.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.9/angular-material.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.9/angular-material.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="form">
<div class="col-md-12">
<label for="inputPassword3" class="col-sm-2 control-label">Školski sat *</label>
<div class="col-sm-10">
<span class="col-sm-2" ng-repeat="period in periods">
<md-checkbox ng-model="model.periods[period]">
{{ period }}. sat
</md-checkbox>
</span>
</div>
<span ng-bind="model.periods | json"></span>
<hr>
<button type="button" class="btn btn-success" ng-click="save()">Save data</button>
</div>
</form>
</body>
</html>
I hope it helps.

angularjs get only selected checkbox

i want to get the selected checkboxes in my loop, for that check box i have to retrive the amount field onclick.
Here is my HTML script :
<div ng-repeat="$item in items">
Amount :<input ng-model="$item.daily_data.payment_amount">
Check : <input type=checkbox ng-model="checkAmount[$item.daily_data.id]" ng-value="$item.id" >
</div>
<input type="button" ng-click="checkNow()" />
The below script showing all check boxes . i want the only selected one.
JS Script :
$scope.checkAmount = {};
$scope.checkNow(){
console.log($scope.checkAmount);
}
First of all to use functions with $scope you should do something like this:
$scope.checkNow = function() {
...
}
or
$scope.checkNow = checkNow;
function checkNow() {
...
}
About your problem:
You could bind the checkboxes to a property (something like checked), so you can have the items that are checked easily in your controller.
Then, to calculate the total of all checked amount , I' suggest you to use Array.prototype.filter() + Array.prototype.reduce().
Here's a demo based on your original code:
(function() {
angular
.module("app", [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
$scope.checkNow = checkNow;
$scope.checkAmount = {};
$scope.items = [
{
"id": 1
},
{
"id": 2
},
{
"id": 3
}
];
function checkNow() {
$scope.total = $scope.items.filter(function(value) {
return value.checked;
}).reduce(function(a, b) {
return a + b.amount;
}, 0);
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="$item in items">
<label>
Amount: <input type="number" ng-model="$item.amount">
</label>
<label>
Check: <input type=checkbox ng-model="$item.checked">
</label>
</div>
<button type="button" ng-click="checkNow()">Check now</button>
<hr>
<label for="total">Total</label>
<input type="number" id="total" disabled ng-model="total">
</body>
</html>

How to dynamically create text box when we click on a link using angularjs

I have a problem to show INPUT field when do some action.
I have BUTTON (Click here) as soon as user made a click event on button i wanted to show input field
I have done this by using jQuery.
Can any one help me in Angular.js
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.boxShow = false;
});
</script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
show box
<div ng-show="boxShow">
<textarea rows="4" cols="50">text</textarea>
</div>
</div>
</div>
https://jsfiddle.net/bxwjpmaa/1/
HTML
<div class="btn btn-primary" ng-click="openTextBox();">Click Me To open text box</div>
<div ng-show="openTextBox == true">
<input type="text"/>
</div>
SCRIPT :
$scope.openTextBox = function () {
$scope.openTextBox = true;
}
please don't take scope variables and function names same
example here
$scope.openTextBox = function () {
$scope.openTextBox = true;
}
//this is not correct as per angular documentation because scope.openTextBox name already assigned to scope function,again its assigning scope variable "$scope.openTextBox = true" here u will get errors when ever u clicked div second time" TypeError: boolean is not a function" it will throw this error.so please dont use which is already assigned scope function dont assign scope variable
see this fiddle url : https://jsfiddle.net/veerendrakumarfiddle/bxwjpmaa/2/
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ol>
<li ng-repeat="element in elements">
<input type="text" ng-model="element.value"/>
</li>
</ol>
<br/>
<b>Click here to add Textbox:</b><br/><input type="button" value="New Item" ng-click="newItem()"/>
<br/>
<br/>
<b>Click here to see ng-model value:</b><br/>
<input type="button" value="submit" ng-click="show(elements)">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var counter=0;
$scope.elements = [ {id:counter, value : ''} ];
$scope.newItem = function(){
counter++;
$scope.elements.push( { id:counter,value:''} );
}
$scope.show=function(elements)
{
alert(JSON.stringify(elements));
}
});
</script>
</body>
</html>

Resources