Apply filter using ng-repeat results - angularjs

I have a problem filtering results depending on ID of previous get request:
$http.get('https://www.immobiliaremartina.it/inc/show_all.php')
.success(function (data) {$scope.results = data;})
.error(function () {alert("Errore di connessione!")})
$http.get('https://www.immobiliaremartina.it/inc/showFoto.php')
.success(function (data) {$scope.fotos = data;})
.error(function () {alert("Errore di connessione!")})
After this two calls I want to show all pics in fotos depending on the ID of results
<div class="slider gal" >
<ul class="slides" >
<li ng-repeat="foto in fotos | filter: result.ID === foto.ID">
<img src="/public/galleria/{{foto.URL}}">
</li>
</ul>
</div>
how is this possible?

You can try the following
js
$scope.data = [];
var fotos = $http.get('https://www.immobiliaremartina.it/inc/showFoto.php')
var results = $http.get('https://www.immobiliaremartina.it/inc/show_all.php')
$q.all([fotos, results]).then(data => {
var fotoResult = data[0];
var resultResult = data[1];
for(i= 0; i< fotoResult.length;i++){
for(j = 0; j < resultResult.length;j++){
if(fotoResult[i].ID === resultResult[j].ID){
$scope.data.push(fotoResult[i]);
}
}
}
});
html
<div class="slider gal" >
<ul class="slides" >
<li ng-repeat="foto in data>
<img src="/public/galleria/{{foto.URL}}">
</li>
</ul>
</div>
the above code waits for the results of both of your http requests and when they are loaded it filters data in your controller and shows filtered data in your html.

Create a function:
$scope.isInResults = function(foto){
return results.filter((result) => result.id === foto.id)
};
and then
<li ng-repeat="foto in fotos | filter: isInResults">
<img src="/public/galleria/{{foto.URL}}">
</li>

Related

Angular - Filtering data based on bootstrap dropdown selection

I'm trying to filter a list based on a selection from a bootstrap dropdown, but cannot seem to get it to work. Here's my code:
<body>
<div class="toolbar-wrapper" >
<div class="btn-group container" role="group" ng-controller="filterController">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
{{filter}}
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li ng-repeat="severity in severityLevels">{{severity}}</li>
</ul>
</div>
</div>
</div>
<div class="logMessages" ng-controller="logController">
<div >
<ul>
<li class="message" ng-repeat="logData in data | filter: filter | limitTo: quantity">
{{logData.timestamp}} : {{logData.severity}} : {{logData.message}}
</li>
</ul>
</div>
</div>
</body>
Javascript:
var app = angular.module('UnifyLog', []);
app.controller('filterController', function($scope) {
$scope.severityLevels = [
'ERROR',
'WARN',
'INFO',
'DEBUG'
];
$scope.filter = '';
$scope.resetFilter = function() {
$scope.filter = '';
};
$scope.changeSeverity = function(severity) {
$scope.filter = severity;
}
})
.controller('logController', function ($scope, $http) {
$http.get("https://clock/settings/get_log_messages", {}).then(
function (response) {
$scope.data = response.data;
},
function (response) {
console.log("fail:" + response);
}
);
$scope.quantity=100
});
I know you can use ng-model data binding with a select directive, but I want to use a bootstrap dropdown.
The code above is updating the scope.filter variable but the list of log messages does not filter.
The http request is getting back a json array with log data objects containing message, timestamp, and severity fields.
Try calling $scope.apply():
$scope.changeSeverity = function(severity) {
$scope.filter = severity;
$scope.apply()
}
Look here for more information, and consider another approach (use real data-binding instead of a custom callback): https://github.com/angular/angular.js/wiki/When-to-use-$scope.$apply()
I would create a customer severity filter like so:
.filter('severityFilter', function () {
return function (input, severity) {
var out = [];
if (input && input != []) {
angular.forEach(input, function (thing) {
if(thing.severity === severity){
out.push(thing);
}
});
}
return out;
}
})
Then apply it like this:
ng-repeat="logData in data | severityFilter: severity | limitTo: quantity">

AngularJS nested loops - how do i get to not display an item when a condition fails in an inner ng-repeat loop

Say I have a nested loop like the code below
<div ng-repeat="m in masters">
<h3> {{m.name}} </h3>
<div ng-repeat="i in items">
<a ng-if="m.url === i.url"> {{i.name}} </a>
</div> </div>
How do I get to not have line 3 <h3> ... </h3> display the name when the condition
<a ng-if"..."> ... </a> fails and return nothing.
use a function to test whether the child condition exists -- so in your controller add a function like:
$scope.itemsHasUrl = function(url) {
for(var i=0;i<$scope.items.length;i++) {
if($scope.items[i].url === url) return true;
}
return false;
}
then in the template
<div ng-repeat="m in masters">
<h3 ng-if"itemsHasUrl(m.url)"> {{m.name}} </h3>
<div ng-repeat="i in items">
<a ng-if="m.url === i.url"> {{i.name}} </a>
</div>
</div>
you may also want to look into filters as you may be able to use the same function to limit the items checked in the interior loop, or using angular-filters groupBy method to avoid a double-loop at all.
good luck!
You can add a function in your controller to check if one of the items has the given url
$scope.checkUrl = function(url, items) {
for (var i = 0; i < items.length; i++) {
if (items[i].url == url) return true;
}
return false;
}
in your template
<h3 ng-if="checkUrl(m.url, items)"> {{m.name}} </h3>
To entertain my original comment, and derelict's answer, here is a .filter() way of doing this.
HTML
<div ng-repeat="m in masters | checkUrl:items">
<h3>{{m.name}}</h3>
<div ng-repeat="i in items | checkUrl:m">
<a>{{i.name}}</a>
</div>
</div>
Javascript
var app = angular.module("myApp", [])
.filter("checkUrl", function () {
return function (items, checkValues) {
return items.filter(function (item) {
if (typeof(checkValues.url) === "string") {
// single item check
return item.url === checkValues.url;
}
// else multiple items check
return checkValues.some(function (value) {
return value.url === item.url;
});
});
};
})
.controller("myCtrl", function ($scope) {
// controller code here ...
}

How can I use filter in more than one ng-repeat?

HTML Code This is used for display images in grid.
I used this link -- http://codepen.io/pulkitsinghal/pen/JjmED/
In this i used 5 ng-repeat tags but i got errors on filter ng-repeat="row in f.images | inSlicesOf:2"
<div class="list itemnew card" ng-repeat="group in groups">
<ion-item class="item item-icon-right" ng-click="toggleGroup(group)" ng-class="{active: isGroupShown(group)}" style="">
<i class="ion-chevron-right pull-right" ng-class="isGroupShown(group) ? 'ion-chevron-down' : 'ion-chevron-right'" style="float:right;"><input type="hidden" ng-model="group.menu_name"></i> {{group.menu_name}}
<div ng-switch on="group.menuid">
<!--Facilitites-->
<div ng-switch-when="8">
<ion-item class="item-accordion item ng-binding ng-hide " ng-show="isGroupShown(group)" style="">
<div class="item bdr-none blue-light" style="margin-top:25px !important;">
<div ng-repeat="facility in group.facilities">
<div ng-repeat="f in facility">
<h2 class="padding-left">{{f.facilities_name}}</h2>
<div class="row" ng-repeat="row in f.images | inSlicesOf:2">
<div class="col col-50" ng-repeat="item in row">
<img src="{{item.img_name}}" class="col col-30" ng-click="showImage('{{item.img_name}}')" />
</div>
</div>
</div>
</div>
</div>
</ion-item>
</div>
</div><!--Switch-->
</ion-item>
</div>
<!-- end ngRepeat: item in group.items -->
Controller
This in controller where i put my filter.
var app = angular.module('test', ['ionic']);
app.filter('inSlicesOf', ['$rootScope',
function ($rootScope) {
makeSlices = function (items, count) {
if (!count)
count = 3;
if (!angular.isArray(items) && !angular.isString(items)) return items;
var array = [];
for (var i = 0; i < items.length; i++) {
var chunkIndex = parseInt(i / count, 10);
var isFirst = (i % count === 0);
if (isFirst)
array[chunkIndex] = [];
array[chunkIndex].push(items[i]);
}
if (angular.equals($rootScope.arrayinSliceOf, array))
return $rootScope.arrayinSliceOf;
else
$rootScope.arrayinSliceOf = array;
return array;
};
return makeSlices;
}]);
app.controller('AboutUsCtrl', function ($scope, $http, $ionicModal) {
$scope.groups = [];
if (window.localStorage.getItem("about") !== null) {
if (window.localStorage.getItem("about") !== "undefined") {
$scope.groups = JSON.parse(window.localStorage.getItem("about"));
}
}
$http.post("json")
.success(function (response) {
if (response.about === undefined) {
if (window.localStorage.getItem("about") !== "undefined") {
$scope.groups = JSON.parse(window.localStorage.getItem("about"));
}
} else {
$scope.groups = response.about;
window.localStorage.removeItem("about");
window.localStorage.setItem("about", JSON.stringify(response.about));
}
}).error(function (data) {
if (window.localStorage.getItem("about") !== "undefined") {
$scope.groups = JSON.parse(window.localStorage.getItem("about"));
}
});
$scope.toggleGroup = function (group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function (group) {
return $scope.shownGroup === group;
};
});
Error in console
For the preference purpose
Error: [$rootScope:infdig] errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…22%3A%22http%3A%2F%2Fkbs-test.com%2Fimages%2Fpages%2Fimg13.jpg%22%7D%5D%5D
at Error (native)
at 127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…-a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:37:416
at n.$digest (127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…-a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:164:96)
at n.$apply (127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:166:269)
at HTMLBodyElement. (127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:137:115)
at HTMLBodyElement.Gf.c (127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…-a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:66:217)
at n (127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…-a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:22:384)
at t (127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…-a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:22:216)
at HTMLDocument.l (127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/…a621-2128fb7dbab1/platforms/ios/www/js/angular/ionic.bundle.min.js:22:1451)

ng-repeat store separate values

I want to store the users vote's inside a cookie, the problem is that inside the ng-repeat I have a value called session.upVoteCount. But it is supposed to be a separate value for each event list item. Is it possible to store each upVoteCount separately and then retrieve them separately again?
<li ng-repeat="session in event.sessions | filter:query | orderBy:sortorder" class="span11">
<div class="row session">
<div class="col-sm-1 well votingWidget">
<div class="votingButton" ng-click="upVoteSession(session)">
<span class="glyphicon glyphicon-arrow-up"></span>
</div>
<div class="badge badge-inverse">
<div>{{session.upVoteCount}}</div>
</div>
<div class="votingButton" ng-click="downVoteSession(session)">
<span class="glyphicon glyphicon-arrow-down"></span>
</div>
</div>
</div>
</li>
and in my controller I have this:
$scope.upVoteSession = function(session) {
session.upVoteCount++;
};
$scope.downVoteSession = function(session) {
session.upVoteCount--;
};
First, I don't recommend to use term 'session', but 'votes'. However, it's your call.
I simplify your problem in this example
http://plnkr.co/edit/l7tQRbuOtEDJetY5eTsf?p=preview
Javascript:
function MyCtrl($scope) {
$scope.votes = {};
$scope.vote = function(key, val) {
$scope.votes[key] = $scope.votes[key] || 0;
$scope.votes[key]+= val;
};
}
Html:
<li ng-repeat="no in [1,2,3,4,5]">
{{no}} : {{votes[no]}} <br/>
upvote
downvote
</li>
Hi guys I solved it myself, I could not get it to work with JSfiddle so I have uploaded the entire thing. Click on server.bat and browser to localhost:8000/eventdetails.html and you will see it working.
https://mega.co.nz/#!1d9yiYiA!zTzdztLAmhVDVYOvvVLINETI2bo_WjxCBteWYm2VUKc
controller:
eventsApp.controller('EventController',
function EventController($scope, $cookieStore, eventData) {
$scope.sortorder = 'name';
var ape = eventData.getEvent();
ape.then(function (banana) {
$scope.event = banana;
angular.forEach(banana.sessions, function (value, key) {
var storecookie = ($cookieStore.get(value.name));
if (typeof storecookie !== "undefined") {
value.upVoteCount = storecookie;
}
});
});
$scope.upVoteSession = function (session) {
session.upVoteCount++;
$cookieStore.put(session.name, session.upVoteCount);
};
$scope.downVoteSession = function (session) {
session.upVoteCount--;
$cookieStore.put(session.name, session.upVoteCount);
};
}
);

AngularJS determine filter in controller

How would I go about setting the filter property on an ng-repeat dynamically?
Here is my template...
<div class="list-group">
<div ng-repeat="article in articles | activeFilter">
<a href="#" class="list-group-item">
<h3 class="list-group-item-heading">{{ article.title }}</h3>
<h4 class="list-group-item-text">{{ article.author }}</h4>
<p class="list-group-item-text">"{{ article.blurb }}"</p>
</a>
</div>
</div>
Where "activeFilter" is a property I want to set via the controller...
...
$scope.activeFilter = 'someFilterType'
...
And the filter looks like this...
.filter('someFilterType', function () {
return function (items) {
var rv = [];
for (var p in items) {
if (items[p].myFilterProp === false)
rv.push(items[p]);
}
return rv;
}
})
I would think I could dynamically change the ng-repeat's filter in this way, but it doesn't seem to be working and I'm not sure why.
Try something like this:
HTML
ng-repeat="article in articles | filter:activeFilter[filter]"
Controller:
$scope.filter = "name1";
$scope.activeFilter = {
name1: $scope.someFilterFunction,
name2: $scope.someOtherFilter,
name3: $scope.andAnother
};
$scope.someFilterFunction = function() {
var rv = [];
for (var p in items) {
if (items[p].myFilterProp === false)
rv.push(items[p]);
}
return rv;
};

Resources