How to select all with ng-checked and ng-model - javascript

I have an Ionic application(it work the same like Angularjs) and I have a little problem.
<ion-list class="list-inset subcategory" ng-repeat="item in shops">
<ion-checkbox class="item item-divider item-checkbox-right" ng-model="selectAll">
{{item}}
</ion-checkbox>
<ion-item ng-repeat="value in data | filter:{shopName: item}" class="item-thumbnail-left" ng-click="openProduct(value)">
...
<div class="row">
<ion-checkbox stop-event='click' ng-model="value.selected" ng-checked="selectAll">{{value.name}}</ion-checkbox>
</div>
...
</ion-list>
When I click on item with ng-model="selectAll" all items is selected. But I have property value.selected. It sets false for each one value. When I click on item with ng-model="value.selected" it changes. But when I want selec all and click on item with ng-model="selectAll" this propety doesn't change.
Help me please.
Note: I have ng-repeat in the ng-repeat. First ng-repeat is for shops, the second is for products. And I have a filter by shopName. And I want select all by shops. Now it works how I want, but doesn't change property value.selected. Value it is produt, item it is shop.

the state of selectAll can be derived from the state of your other check boxes so it should not be stored as a seperate field.
You could use a getterSetter on the selectAll model to determine weather it should be checked. e.g.
<input type="checkbox" ng-model="selectAll" ng-model-options="{getterSetter: true}"/>
JS
var getAllSelected = function () {
var selectedItems = $scope.Items.filter(function (item) {
return item.Selected;
});
return selectedItems.length === $scope.Items.length;
}
var setAllSelected = function (value) {
angular.forEach($scope.Items, function (item) {
item.Selected = value;
});
}
$scope.selectAll = function (value) {
if (value !== undefined) {
return setAllSelected(value);
} else {
return getAllSelected();
}
}
http://jsfiddle.net/2jm6x4co/

you can use ngClick on the item with ng-model="selectAll". you can call a function in ng-click and then make selected=true for all other items where ng-model="value.selected".

Related

Cannot bind ngModel to p-dropdown value (Angular)

I using PrimeNg dropdown
Here is html of template
<div>
<label>{{ l('Portfolio') }}</label>
<p-dropdown
[(ngModel)]="property.portfolioId"
[disabled]="!landlordPortfolios.length"
[options]="landlordPortfolios"
autoWidth="false"
[style]="{ width: '100%' }"
name="landlordPortfolio"
[autoWidth]="true"
></p-dropdown>
</div>
I get values for dropdown via this method
getLandlordPortfoliosById(landlordId: number): void {
this.landlordPortfolios = [];
this._landlordPortfolios.getPortfolioDropdownValuesById(landlordId).subscribe(result => {
result.items.forEach(value => {
this.landlordPortfolios.push({
label: value.name,
value: value.id,
});
});
});
}
And call it like this
if (this.property.landlordId) {
this.getLandlordPortfoliosById(this.property.landlordId);
this.initLandlordSuggestionsById(this.property.landlordId);
}
For example I have landlordId = 1 and selected option for dropdown must be also with id = 1.
Here is result
But I get selected item in dropdown, just blank field, and I see all options when click dropdown. Where can be my problem?
So problem was in data request/get
if I set *ngIf to dropdown, like this *ngIf = "landlordPortfolios.length" and delete [disabled], all going well.

Retreiving filteredItems from uib-typeahead custom popup doesn't work

Retreiving filteredItems from ng-repeat in controller through $scope doesn't work
I am trying to get filtered items from ng-repeat but I get undefined when console logging the value of $scope.filteredItems. I even tried the solution provided in Can't get the filtered items from my filtered list inside a modal but it didn't work either.
The ng-repeat is in a uib-typeahead custom popup templates for typeahead's dropdown. I am trying to get the filtered value in the parent controller.
example-input.component.ts
/////////////////////////////////
componentController.$inject = ['$scope', 'exampleDataService'];
function componentController($scope, exampleDataService) {
var someInput = this;
someInput.typedText = '';
someInput.onKeyPress = onKeyPress;
return;
/////////////////////////////////
//controller implementation detail
/////////////////////////////////
function onKeyPress(){
console.log($scope.filteredItems); // prints undefined
}
}
UIB-Typeahead Custom Template for Popup
<script type="text/ng-template" id="input-custom-template.html">
<ul class='dropdown-menu' ng-show='isOpen() && !moveInProgress'
ng-style="{top: position().top+'px', left: position().left+'px'}"
role='listbox' aria-hidden='{{!isOpen()}}' match-limit in-view-container>
<li style="max-height:0;overflow:hidden"><span in-view="$inview && matchLimit.reset()"> </span></li>
<li ng-repeat='match in (filteredItems = (matches | someMatchSort:query | limitTo:matchLimit.value)) track by some.model.example '
ng-class='{active: isActive($index) }'
ng-mouseenter='selectActive($index)'
ng-click='selectMatch($index, $event)'
role='option' id='{{::match.id}}'
in-view="!$inview && isActive($index) && scrollTarget.scrollIntoView()"
scroll-target
>
<div uib-typeahead-match index='$index' match='match'
query='query' template-url='templateUrl'>
</div>
</li>
</ul>
</script>
<input type="text" ng-model="someInput.typedText" typeahead-min-length="1"
uib-typeahead="option.example as option.value for option in someInput.options | filter:{value:$viewValue}"
class="form-control input-text-example icon-search"
placeholder="example"
typeahead-popup-template-url="input-custom-template.html"
ng-keypress="someInput.onKeyPress()"/>
If you need any additional info pls let me know. There is also a filter called someMatchSort.filter.ts but I'm not sure if it makes difference to add it here. Anyways let me know, I will update my question
You might want to use ng-keyup in your case.
Then in your component write like so
function onKeyPress(){
console.log($scope.$$childHead.matches.length);
}

ng-show with localStorage choice

I have a ionic list which shows the checked items from another list, but I want to show a message if the list is empty.
The code is:
<ion-item ng-repeat='(place, checked) in localStorage.options' ng-if="checked" class="item item-body">
How would I do the ng-show, as this is not the standard ng-repeat.
try this :
Controller:
$scope.isEmptyObjectEmpty = function(object) {
for(var i in object) {
return true;
}
return false;
};
Html:
<div class="item item-text-wrap"
ng-if="!isEmptyObjectEmpty(localStorage.options)">
list is empty(msg)
</div>

How to filter through a table using ng-repeat checkboxes with Angularjs

Once upon a time this was working but somehow it's broken. I want to be able to produce checkboxes using ng-repeat to get as many checkboxes as required based on stored data and use these to filter through a table produced.
Additionally I don't want identical values for the checkboxes to be repeated.
I have made a plnkr with the code.
<div class="row">
<label data-ng-repeat="x in projects">
<input
type="checkbox"
data-ng-true-value="{{x.b}}"
data-ng-false-value=''
ng-model="quer[queryBy]" />
{{x.b}}
</label>
</div>
http://plnkr.co/edit/RBjSNweUskAtLUH3Ss6r?p=preview
So in summary.
Checkboxes to filter Ref.
Checkboxes to be unique.
Checkboxes to be made based off ng-repeat using Ref.
Okay, here's how to do it.
First, let's add a couple of lines of CSS in your to make sure all the checkboxes are visible:
<style>
.row { margin-left: 0px }
input[type=checkbox] { margin-left: 30px; }
</style>
Next, add the following lines to your controller:
app.filter('unique', function() {
return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
})
app.controller("maincontroller",function($scope){
$scope.query = {};
$scope.quer = {};
$scope.queryBy = '$';
$scope.isCollapsed = true;
$scope.selectedRefs = [];
$scope.myFilter = function (item) {
var idx = $scope.selectedRefs.indexOf(item.b);
return idx != -1;
};
$scope.toggleSelection = function toggleSelection(id) {
var idx = $scope.selectedRefs.indexOf(id);
if (idx > -1) {
$scope.selectedRefs.splice(idx, 1);
}
else {
$scope.selectedRefs.push(id);
}
};
Phew.
For some reason, your Plunkr's version of AngularJS didn't recognise the unique attribute, so I added one to your controller.
Finally, change your html to this:
<div class="row">
<label data-ng-repeat="x in projects | unique:'b' | orderBy:'b'" >
<input
id="x.b"
type="checkbox"
ng-click="toggleSelection(x.b)"
ng-init="selectedRefs.push(x.b)"
ng-checked="selectedRefs.indexOf(x.b) > -1" />
{{x.b}}
</label>
</div>
... and your ng-repeat to this...
<tr ng-click="isCollapsed = !isCollapsed" ng-repeat-start="x in projects | filter:myFilter | orderBy:orderProp">
If you're interested in knowing how this works, add these lines:
<div style="margin:10px 10px 30px 10px">
<pre>{{ selectedRefs }} </pre>
</div>
I love this trick: you can see the exact contents of our "selectedRefs" array, and see it change as we tick/untick our checkboxes. This really helps when developing/testing our bindings!
As you can see, these changes use the new unique function to get your list of distinct values from your project array, and when the page first loads, we push all of the values into our new "selectedRefs" array.
["123","321","456","654","789","987"]
Then, as you tick/untick the checkboxes, we add/remove that item from this list.
Finally, we use that filter in the ng-repeat.
ng-repeat-start="x in projects | filter:myFilter | orderBy:orderProp"
Job done !
Update
If you wanted to start off with all checkboxes unticked, then it's a simple change. Just remove this line...
ng-init="selectedRefs.push(x.b)"
..and change the myFilter function to show all items initially..
$scope.myFilter = function (item) {
if ($scope.selectedRefs.length == 0)
return true;
var idx = $scope.selectedRefs.indexOf(item.b);
return idx != -1;
};
And to add a "Clear all" button, simply add a button to your form which calls a function in your AngularJS controller like this..
$scope.clearAll = function () {
$scope.selectedRefs = [];
};
(I haven't tested these suggestions though.)
ng-false-value directive needs a value set. Try ng-false-value='false' or ng-false-value='null' (in fact you can skip this one entirely if it has to just be a falsy value and not something concrete, like a string or certain number).
As you've pointed out in the comments, after selecting and then clearing the checkboxes, all rows are filtered out. It happens because unchecking the checkbox will set its value to false, and this does not agree with your entities' values (as you probably know, just stating it for others).
Therefore you do need to set this value to empty string in the end. That'd be the way:
$scope.$watch('quer.$', function () {
if ($scope.quer.$ === false) {
$scope.quer.$ = '';
}
});

Filter variable not updating in controller angularjs

Hi Im attempting to build functionality around the length of a filter in angularjs, and although its working as it should in the view, in the controller the variable seems to stay outdated...
When I click on the div below it filters a list and calls the filterby function. The output of the length of the newly filtered list updates in the view correctly. However in the function itself I have a log set and it is still showing the old length when I click on the div.
<div ng-repeat="filter in filters" ng-click="filterby(filter.filter_type)">{{filter.filter_type}}</div>
<ul>
<li ng-repeat="event in filtered = (events | filter:query) | orderBy:'-event_date' ">
<span >{{event.event_date}},{{event.event_name}}, {{event.event_venue}}, {{event.event_description}} </span>
</li>
</ul>
<br />Length of filtered items {{filtered.length}}
And my view....
$scope.filterby = function(filterby) {
if (filterby == 'ALL') {
$scope.query = '';
}
else {
$scope.query = filterby;
}
console.log($scope.filtered.length);
};
My filter data:
$scope.filters = [
{'filter_type' : 'ALL'},
{'filter_type' : 'Macnass'}
];
EDIT: Ok its not that it nots working at all, its just showing the previous value, as if its one click behind all the time, so its something to do with the fact that the variable in the view is updated after the list is made. but Im not sure how to go about insuring the variable in the controller is the latest value.
Plunker: http://plnkr.co/edit/u7KpqYx8gDwaaXEvGeMn?p=preview
check out the plunker
added below
$scope.filtered = $filter('filter')($scope.events, $scope.query)
in $scope.filterby function

Categories

Resources