Angular 1.4
I have a simple ng-repeat with a check box. The goal is to have the customer.Id added into the $scope.holdsChosenCustomerIds. I need $scope.holdsChosenCustomerIds to be dumb array like [3,78,445,789], basically whatever the user selects.
$scope.holdsChosenCustomerIds= [];
<div ng-repeat="customer in customers">
<input type='checkbox' ng-model="holdsChosenCustomerIds[$index]==???" ????????? />
</div>
stuck at this point
Just use instance of ng-repeat as model
Like this
<div ng-repeat="customer in customers">
<input type='checkbox' ng-model="customer.isChecked" />
</div>
You can get info of checked item from $scope.customers
If you need checked true item
you can try like this
$scope.holdsChosenCustomerIds= $scope.customers.filter(function(x){ return x.isChecked; });
You can write like this in your HTML using ng-change:
<div ng-repeat="customer in customers">
<input type='checkbox' ng-model="customer.selected" ng-change="selectUnselect()" />
</div>
And in your controller:
$scope.selectUnselect = function() {
var customer = this.customer;
if (customer.selected) {
$scope.holdsChosenCustomerIds.push(customer.id);
} else {
var idIndex = $scope.holdsChosenCustomerIds.indexOf(customer.id);
if (idIndex > -1) {
$scope.holdsChosenCustomerIds.splice(idIndex, 1);
}
}
};
Related
I have an input element being populated using the *ngFor loop fetching the data from another array. On selecting multiple checkboxes, I need their values to be pushed into my empty array 'selectedArr'.
Find below the code:
import { Component } from "#angular/core";
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "CodeSandbox";
toDo = ["Test", "Eat", "Sleep"];
task: string;
addTask(task: string) {
this.toDo.push(task);
}
selectedArr = [];
deleteValue() {}
addSelected(i) {
let checkId = document.getElementsByClassName("i");
console.log(checkId);
if (checkId.checked === true) {
this.selectedArr.push(i);
}
console.log(this.selectedArr);
}
}
<div>
<div class="form-group">
<label>Add a Task: </label>
<input class="form-control" type="text" [(ngModel)]="task" />
</div>
<button (click)="addTask(task)">Add</button>
<br />
<br />
<div>
My To Do List:
<ul>
<li *ngFor="let todo of toDo, index as i">
<input class="i" type="checkbox" (click)="addSelected(i)" />
{{todo}}
</li>
</ul>
</div>
<div class="btn class">
<button class="btn btn-primary" (click)="deleteValue()">Delete</button>
</div>
</div>
Try like this:
.html
<li *ngFor="let todo of toDo, index as i">
<input class="i" type="checkbox" [(ngModel)]="checked[i]" (ngModelChange)="addSelected(todo,$event)" />
{{todo}}
</li>
.ts
checked = []
selectedArr = [];
addSelected(item,evt) {
if (evt) {
this.selectedArr.push(item);
}else {
let i = this.selectedArr.indexOf(item)
this.selectedArr.splice(i,1)
}
}
Working Demo
The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). Since you are passing the index, you can access the clicked element like:
addSelected(i) {
let checkId = document.getElementsByClassName("i")[i];
console.log(checkId);
if (checkId.checked) {
this.selectedArr.push(i);
} else {
// Remove the index from selectedArr if checkbox was unchecked
let idx = this.selectedArr.indexOf(i)
if (idx > -1) this.selectedArr.splice(idx, 1)
}
console.log(this.selectedArr);
}
please, the things easy works easy. You needn't actually manually the array. You should use a function (*)
get selectedArray()
{
return this.toDo.filter((x,index)=>this.checked[index])
}
<li *ngFor="let todo of toDo, index as i">
<!--remove (ngModelChange) -->
<input class="i" type="checkbox" [(ngModel)]="checked[i]" />
{{todo}}
</li>
{{selectedArray}}
(*) this allow you "start" the app with some selected
I Have two forms.In these forms am getting input from the first form and show that in the second form, Which means if the user selected the currency from the dropdown, i need to pass id and the the currency name. But show only the currency name in the second form. I tried one method (dont know whether it is correct or not) it is showing the id only. am new to angular. is there anyway to solve this?
HTML
<div class="row text-center" ng-show="firstform">
<form name="validation">
<label>Currency</label>
<select ng-model="CurrencyId" ng-selected="CurrencyId" class="form-control" id="CurrencyId">
<option ng:repeat="CurrencyId in currencyList" ng-selected="selectedCurrencyType == CurrencyId.id" value={{CurrencyId.currencyId}}>{{CurrencyId.name}}</option>
</select>
<label>Grade</label>
<select ng-model="GradeId" ng-selected="GradeId" class="form-control" id="GradeId">
<option ng:repeat="GradeId in RaceGradeList" ng-selected="selectedGrade == GradeId.id" value={{GradeId.id}}>{{GradeId.gradeName}}</option>
</select>
<button type="submit"value="add" ng-click="savedetails()" />
</form>
</div>
<div class="row text-center" ng-show="secondform">
<form name="thirdform">
<ul >
<li><p>Currency:{{CurrencyId}}</p> </li>
<li><p>Grade:{{GradeId}}</p> </li>
</ul>
</form>
</div>
angular controller
$scope.savedetails = function () {
$scope.firstform= false;
$scope.secondform = true;
}
This is the most simplest solution that you can go for. Instead of having the value={{CurrencyId.currencyId}} set it as value={{CurrencyId.name}} for the options in the dropdown and you are good to go. Below is the demo for the same. But if you want to save currencyId as the value then you will have to iterate over the array and find the name based on the selected currencyId and then show that in the view.
UPDATE
Updated the code to have the currencyId being stored as the selected value and then based on that showing the name in the view.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.currencyList = [{
currencyId: 1,
name: "INR"
},
{
currencyId: 2,
name: "$"
},
{
currencyId: 3,
name: "#"
}
];
$scope.currencyChanged = function() {
var selectedCurrency;
for (var i = 0; i < $scope.currencyList.length; i++) {
var thisCurr = $scope.currencyList[i];
if ($scope.CurrencyId == thisCurr.currencyId)
selectedCurrency = thisCurr.name;
}
return selectedCurrency;
}
$scope.firstform = true;
$scope.savedetails = function() {
$scope.firstform = false;
$scope.secondform = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div class="row text-center" ng-show="firstform">
<form name="validation">
<label>Currency</label>
<select ng-model="CurrencyId" ng-selected="CurrencyId" class="form-control" id="CurrencyId">
<option ng:repeat="CurrencyId in currencyList" ng-selected="CurrencyId == CurrencyId.currencyId" value={{CurrencyId.currencyId}}>{{CurrencyId.name}}</option>
</select>
<button type="button" value="add" ng-click="savedetails()">Save Details</button>
</form>
</div>
<div class="row text-center" ng-show="secondform">
<form name="thirdform">
<ul>
<li>
<p>Currency:{{currencyChanged()}}</p>
</li>
</ul>
</form>
</div>
</body>
Hope it helps :)
You can use ng-options , its very flexiable where we can display one value and select either entire object or any specific property.
Please check below plunker , hope it meets your requirement
https://plnkr.co/edit/JQjmAwk62R8rfAlTZ696?p=preview
<select ng-model="CurrencyId" ng-options="currency.id for currency in currencyList" class="form-control" id="CurrencyId" >
</select>
For more details on ng-options , go through below video
https://www.youtube.com/watch?v=vqx3zCy4d3I
try
<li><p>Currency:{{CurrencyId.name}</p> </li>
In my App I have an $http.get() request that stores data into the array $scope.requirements and a boolean into $scope.requirementsFulfilled.
I have a directive using the same controller as the page. They both do an ng-repeat on the $scope.requirements. When the requirementsFulfilled is false only the directive version shows, when true only the containing page.
The problem is when I envoke $http.get() after the first time the results are only being stored in the directive version. How do I make sure this information is bound to both?
Within the controller...
$scope.requirementsFulfilled;
$scope.requirements = [];
$scope.getRequirements = function(url) {
$http.get(url)
.then(function(res){
$scope.requirements = res.data.requirements;
$scope.setFulfilled( res.data.fulfilled );
});
};
$scope.submitRequirementScan = function() {
if ($scope.checkRequirement() ) {
$scope.getRequirements('tempjson/requiredPartsFulfilled.json');
}
};
$scope.setFulfilled = function( inputFulfilled ) {
$scope.requirementsFulfilled = inputFulfilled;
};
$scope.getRequirements('tempjson/requiredParts.json');
The page gets the requirements and populates the page. Then the user takes actions which fires off checkRequirement() and then fetches the new json if true. From this point only the directive is updating.
I believe that a child scope is being created for the directive, but I am not certain exactly what is happening. Here is the entirity of the directive info.
.directive("operationRequirements", function () {
return {
restrict: "E",
templateUrl: "requirements/requirements.html"
};
});
What is going on with it?
edit - Html for the directive
<div class="col-md-6 col-md-offset-3">
<h5>Scan Requirements</h5>
<form ng-submit="submitRequirementScan()" ng-controller="operationCtrl">
<label> <div class="glyphicon glyphicon-barcode ng-hide" ng-hide="requirement.scanned"></div>
<input type="text" ng-model="text" name="text" placeholder="Scan Barcode" autofocus /></label>
<input type="submit" id="submit" value="Submit Scan" class="btn" />
<table class="table table-hover">
<tr ng-repeat="requirement in requirements | filter : unScannedFilter">
<td>{{$index + 1 }}</td>
<td>
<div class="glyphicon glyphicon-barcode ng-hide" ng-hide="requirement.scanned"></div>
<div class="glyphicon glyphicon-check ng-show" ng-show="requirement.scanned"></div>{{requirement.scanned}}
<div class="col-md-4">
<input type="checkbox" ng-model="requirement.scanned">
</div>
</td>
<td>{{requirement.partId}} - {{requirement.partDescription}}</td>
</tr>
</table>
</form>
</div>
edit 2 -- Html that invokes the directive operation-Requirements and the on page display of the requirements hidden with ng-show.
<div class="row" ng-hide="requirementsFulfilled" >
<operation-Requirements></operation-Requirements>
</div>
<div class="col-md-12" ng-show="requirementsFulfilled">
<table class="table table-hover">
<tr ng-repeat="requirement in requirements">
<td>{{$index + 1 }}</td>
<td>
<div class="glyphicon glyphicon-barcode ng-hide" ng-hide="requirement.scanned"></div>
<div class="glyphicon glyphicon-check ng-show" ng-show="requirement.scanned"></div>
</td>
<td>{{requirement.partId}} - {{requirement.partDescription}}</td>
</tr>
</table>
</div>
So maybe this will help point you in the right direction. What I've done is pulled out the requirements stuff into its own service. Now you have a singleton that handles everything that deals with parts. When its updated in one place its updated everywhere. The directive no longer needs that other controller.
http://plnkr.co/edit/Nej79OI3NrKcrkMNix3D?p=preview
app.service('partsService', function() {
return {
requirementsFulfilled: false,
requirements: [],
getRequirements: function () {
this.requirements.push({partId: 1, partDescription: 'Some Desc', scanned: false});
this.requirements.push({partId: 2, partDescription: 'Some Desc 2', scanned: true});
},
submitScan: function (id) {
this.requirements.filter(function (part) {
return part.partId === id;
}).map(function (part) {
part.scanned = true;
});
this.requirementsFulfilled = this.requirements.filter(function (part) { return !part.scanned }).length === 0;
}
};
});
**Hi,i am filtering the array data from textbox but the code is not working properly can any one help me please.the data from back end
self.AdminLineDetails = function(data) {
$scope.details = [];
$scope.details = data.GoalData;
console.log(data);
}
<div class="row">
<div class="col-md-12">
<input ng-model="query" type="text" class="form-control" placeholder="Filter by name or number">
</div>
<div>
<tbody>
<tr ng-repeat="detail in details|filter:query">
<td>{{detail.firstName}}
</td>
<td>{{detail.lastName}}
</td>
<td>{{detail.mdn}}
</td>
</tr>
</tbody>
</div>
**
You can specify on which property you are trying to filter, do something like
<tr ng-repeat="detail in details|filter: {firstName: query}">
<input type="text" ng-model="search">
<ul ng-repeat="oneauth in authorisations[0]">
<li ng-repeat="entry in oneauth | nameFilter:search">{{entry.auth.name}}</li>
</ul>
JS
var app = angular.module('myapp', [], function () {});
app.controller('AppController', function ($scope) {
$scope.authorisations = [{
"authorisations":[
{
"auth":{
"number":"453",
"name":"Apple Inc."
}
},
{
"auth":{
"number":"123",
"name":"Microsoft Inc."
}
}]
}];
});
app.filter('nameFilter', function(){
return function(objects, criteria){
var filterResult = new Array();
if(!criteria)
return objects;
for(index in objects) {
if(objects[index].auth.name.indexOf(criteria) != -1) // filter by name only
filterResult.push(objects[index]);
}
console.log(filterResult);
return filterResult;
}
});
Check this sample
http://jsfiddle.net/yctchgnk/
I can't seem to figure out how to have another checkbox that selects all and deselects all boxes.
JSFIDDLE
<div ng-controller="tempCtrl">
<input type="checkbox" ng-model="selectAllOptions" ng-click="selectAll()" /> Select/Deselect All
<li ng-repeat="t in parameters.myMainOptions.teams">
<input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
<button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
{{form.selectedTeams}}
</pre>
</div>
var myApp = angular.module('myApp', []);
myApp.controller("tempCtrl", function ($scope) {
$scope.form = {
selectedTeams: {}
};
$scope.parameters = {
myMainOptions: {
teams: ['angels', 'giants', 'orioles', 'bluejays', 'athletics']
}
};
$scope.selectAll = function() {
//This is where I'm stuck
}
});
Here's a working plunkr of a simple select/deselect all checkbox:
plunkr
Controller
$scope.checkboxes = [
{
selected: false
},
{
selected: false
},
{
selected: false
}
];
// Check/uncheck all boxes
$scope.checkAll = function () {
angular.forEach($scope.checkboxes, function (obj) {
obj.selected = $scope.selectAll;
});
};
View
<p>Check all</p>
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<br />
<p>Checkboxes</p>
<div ng-repeat="checkbox in checkboxes track by $index">
<input type="checkbox" ng-model="checkbox.selected" />
<label ng-show="checkbox.selected">Checkbox {{ $index+1 }} selected!</label>
</div>
First, you should make teams an array of objects like this
Controller:
$scope.parameters = {
myMainOptions: {
teams: [{name: 'angels'}, {name: 'giants'}, {name: 'orioles'}, {name:'bluejays'}, {name: 'athletics'}]
}
};
This is a better approach because, now, you can add a selected attribute to each team object.
Then you should set ng-model for each team checkbox to something like team.selected like this:
View:
<li ng-repeat="team in parameters.myMainOptions.teams">
<input ng-model="team.selected" type="checkbox" />
{{team}}
</li>
Now, if you check the angels checkbox, the object will change to {name: 'angels', selected: true}
Then your selectAll function will look like this:
Controller:
$scope.selectAll = function () {
angular.forEach($scope.parameters.myMainOptions.teams, function (team) {
team.selected = $scope.selectAllOptions;
});
};
You could do forEach on $scope.parameters.myMainOptions.teams array and then set $scope.form.selectedTeams value in the loop. Also use ng-change instead of ng-click.
Markup
<input type="checkbox" ng-model="selectAllOptions" ng-change="selectAll()" />Select/Deselect All
<li ng-repeat="t in parameters.myMainOptions.teams">
<input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
<button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
{{form.selectedTeams}}
</pre>
Code
$scope.selectAll = function () {
angular.forEach($scope.parameters.myMainOptions.teams, function (value, index) {
$scope.form.selectedTeams[value] = $scope.selectAllOptions; //setting selectAll variable value
})
}
Working Fiddle