angularjs get only selected checkbox - angularjs

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>

Related

Writing an adding function in AngularJS

I'm new to AngularJS and I am doing some tutorials to get in touch with it. While I'm doing the tutorials I have modified the code a bit to get a better feeling of what's behind. My code consists of two parts, which have nothing to do with each other.
The first one is a simple user input and based on that a list gets filtered. This is working fine.
However, in the second part I was trying to implement a simple adding function where the user can give an input and based on that the sum of two numbers is calculated. This part is not working at all. The numbers are being recognised as strings. The code is basically from this source here. When I copy the whole code and run it, it works fine, but when I modify it a bit it doesn't.
I want to understand why my code isn't working. To me there is nearly no difference. So I think that I eventually misunderstood the concept of angularjs. But I can't figure out where the error could be.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function TodoCtrl($scope) {
$scope.total = function () {
return $scope.x + $scope.y;
};
}
</script>
</head>
<body data-ng-app>
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</body>
</html>
Several things to change...
First you need to create a module:
var app = angular.module("myApp", []);
Then you need to define a module e.g. myApp on the ng-app directive.
<body data-ng-app="myApp">
Then you need to add TodoCtrl to the module:
app.controller("TodoCtrl", TodoCtrl);
Also check that both $scope.x and $scope.y have values, and make sure that they are both parsed as integers, otherwise you will get string concatenation ("1"+"1"="11") instead of addition (1+1=2)!
$scope.total = function () {
return ($scope.x && $scope.y)
? parseInt($scope.x) + parseInt($scope.y)
: 0;
};
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
(function(){
var app = angular.module("myApp", []);
app.controller("TodoCtrl", TodoCtrl);
function TodoCtrl($scope) {
$scope.total = function () {
return ($scope.x && $scope.y)
? parseInt($scope.x) + parseInt($scope.y)
: 0;
};
}
}());
</script>
</head>
<body data-ng-app="myApp">
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</body>
</html>
As mentioned in the above two answers adding TodoCtrl as controller instead function will make the snippet work.
REASON:
Angularjs framework above 1.3 does not support global function which means declaring controller as function wont work.
In your code snippet, you are using angular version 1.5, which needs the controller to be defined.
DEMO
angular.module("app",[])
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" >
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</div>
you need to define the TodoCtrl as controller instead function
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
Demo
angular.module("app",[])
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" >
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</div>

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.

ng-options filter based on text input value

I have a select drop down in Angular based HTML like below. The requirement is to filter the drop down values based on the text the user enter in a text input box. The drop down value in this select is op
How do I add the filter.
<select class="form-control" size="12" data-ng-model="selItem.SelectedItems"
ng-options="option as displaycodeandlabel(option,selItem.isCodeonLabel)disable when option.disabled==true for option in ::a.sData"></select>
Not sure about your data structure, but generally you can just use the native filter.
Here's a working demo:
(function() {
angular
.module('app', [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
$scope.a = {};
$scope.a.sData = [
{
"vm":"0000",
"dm":"U.S. city average",
"disabled":false
},
{
"vm":"0100",
"dm":"Northeast urban",
"disabled":false
},
{
"vm":"0200",
"dm":"Midwest urban",
"disabled":false
}
];
$scope.displayCodeandLabel = function(item, displayCode) {
return displayCode ? item.vm + " " + item.dm : item.dm;
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body ng-controller="MainCtrl">
<div class="col-md-12">
<label for="search">Search</label>
<input type="text" id="search" class="form-control" placeholder="Search" ng-model="search">
<hr>
<select class="form-control" size="12" data-ng-model="selItem.SelectedItems" ng-options="option as displayCodeandLabel(option, selItem.isCodeonLabel)
disable when option.disabled == true for option in a.sData | filter: search"></select>
</div>
</body>
</html>

validate dynamic form before submitting angular

I'm dynamically creating forms with ng-repeat and they have some validation attributes (simplified version):
<div class="row" ng-repeat="defect in model.defects">
<form name="form_{{defect.id}}" novalidate>
<input ng-model="defect.name" required/>
<input type="submit" ng-click="saveDefect(defect)"/>
</form>
</div>
Basically what I want to do is this:
$scope.saveDefect = function (defect) {
if ($scope.<how to get the form name here>.$invalid) {
return;
}
}
Since the form name has been created dynamically with an id how do I access it? Other ways of doing the same are also welcome ofcourse :)
You can use the bracket notation to access it :
$scope["form_"+defect.id]
What I advise you to do is :
var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
$scope.forms = {};
$scope.list = [{id: 1}, {id: 2}];
$scope.save = function(item) {
if ($scope.forms["form_" + item.id].$invalid) {
alert("error on form_" + item.id);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="App" ng-controller="Ctrl">
<div class="row" ng-repeat="item in list">
<form name="forms.form_{{item.id}}" novalidate>
<input ng-model="item.name" required/>
<input type="submit" ng-click="save(item)" />
</form>
</div>
</body>

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