So I am trying to use the orderby function of angularjs. Currently I have an original data set.
$scope.customers = [
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"}
];
$scope.reverse= false;
$scope.toggleOrder = function(){
$scope.reverse=!$scope.reverse;
}
If I use the following to display my customers, I would get the array reverse ordered by the city. Currently I could click on the toggle button and reverse the array if wanted to.
<button ng-click="toggleOrder()">ToggleReverse</button >
<li ng-repeat="x in customers | orderBy : 'city': reverse">{{x.name + ", " + x.city}}</li>
But now the issue is if I didn't want the orderBy function at all. If I wanted to get my original customers data without any order how could I do that with the same toggleOrder function?
For instance, When I load the data it would be the original array. If 1st click of the toggleOrder button, it would sort in based on city, 2nd click of the toggleOrder button would reverse sort the city, and third click of the toggleOrder button would have no sort and give me the original array, and so on.
If the orderBy function isn't the best to go by let me know.
Any help would be great!
I'm not sure why you want to add this feature on your application, but here you go:
(function() {
'use strict';
angular
.module('app', [])
.constant('BUTTON_VALUES', {
1: 'Ascending',
2: 'Descending',
3: 'No order',
})
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', 'BUTTON_VALUES'];
function MainCtrl($scope, BUTTON_VALUES) {
$scope.customers = [
{
"name": "Bottom-Dollar Marketse",
"city": "Tsawassen"
},
{
"name": "Alfreds Futterkiste",
"city": "Berlin"
},
{
"name": "Bon app",
"city": "Marseille"
},
{
"name": "Cactus Comidas para llevar",
"city": "Buenos Aires"
},
{
"name": "Bolido Comidas preparadas",
"city": "Madrid"
},
{
"name": "Around the Horn",
"city": "London"
},
{
"name": "B's Beverages",
"city": "London"
}
];
$scope.btnValue = BUTTON_VALUES[3];
$scope.reverse = true;
$scope.orderParam = '';
var increment = 0;
$scope.toggleOrder = function() {
increment++;
$scope.btnValue = BUTTON_VALUES[increment];
switch (increment) {
case 1:
case 2:
$scope.orderParam = 'city';
$scope.reverse = !$scope.reverse;
break;
case 3:
$scope.orderParam = '';
increment = 0;
break;
}
}
}
})();
<!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">
<button ng-click="toggleOrder()">{{btnValue}}</button>
<pre ng-bind-template="Order - {{orderParam}}"></pre>
<pre ng-bind-template="Reverse? {{reverse}}"></pre>
<hr>
<li ng-repeat="x in customers | orderBy : orderParam: orderParam && reverse">{{x.name + ", " + x.city}}</li>
</body>
</html>
Note: I added a constant as an example to demonstrate how you can handle your button name.
I hope it helps.
So, you want the original order the third time you click on the order by button. Seems doable but complicated. Maybe instead you should have another button that is labeled "original order" and a hidden column that lists the index of your original order. Pushing that button orders by that original index.
/edited I rather use another approach of angualrjs filters which is basically taking string as param and matching it to the object in list.
jsfiddle.net/2q14sryb
Hope it works!
Related
I've been struggling to filter two different arrays, one with the checkbox values and another with whole data. In other terms, first array contains the field values from a sharepoint list and the second array contains the items from same sharepoint list. How can I filter based on the checkbox selected. Here is my code:
<div ng-repeat="x in processes">
<input type="checkbox" ng-model="filteredData"/>{{x}}
</div>
<div ng-repeat = "y in toBeFiltered | filter: {filteredData : true}">
<span class="title">{{y.Title}}</span>
<span class="process"> {{y.process}}</span>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.processes = [
"Alfreds Futterkiste",
"Berglunds snabbköp",
"Centro comercial Moctezuma",
"Ernst Handel",
];
$scope.toBeFiltered = [{
"Title": "title1",
"process": ["Alfreds Futterkiste"]
}, {"Title" : "title2",
"process": ["Alfreds Futterkiste, Berglunds Snabbkop"]
},{"Title" : "title2",
"process": ["Alfreds Futterkiste, Berglunds Snabbkop,Ernst Handel,
Centro Comercial Moctezuma"]
}];
});
</script>
I tried using ng-model, but that didn't work. Please help. Thanks!
As a first step, you need to provide value to the check box inputs which will be set in the ng-model, when the check box is checked.
First of all you need to keep track of selected options, so I added checked property to each processes object, which then ng-model change it's value.
second I changed the two arrays which were like this
["Alfreds Futterkiste, Berglunds Snabbkop,Ernst Handel, Centro Comercial Moctezuma"]
from one long value to
["Alfreds Futterkiste", "Berglunds snabbköp","Ernst Handel", "Centro comercial Moctezuma"]
last you need to define custom filter function, in my case containFn which checks each toBeFiltered item and see if some of this item's processes is contained in processes array with condition that its checked == true
angular.module('myApp', []).controller('myCtrl', function($scope){
$scope.processes = [
{name: "Alfreds Futterkiste", checked: false},
{name: "Berglunds snabbköp", checked: false},
{name:"Centro comercial Moctezuma", checked: false},
{name: "Ernst Handel", checked: false}
];
$scope.toBeFiltered = [{
"Title": "title1",
"process": ["Alfreds Futterkiste"]
}, {"Title" : "title2",
"process": ["Alfreds Futterkiste", "Berglunds snabbköp"]
},{"Title" : "title2",
"process": ["Alfreds Futterkiste", "Berglunds snabbköp","Ernst Handel", "Centro comercial Moctezuma"]
}];
$scope.containFn = function(item){
var found = false;
item.process.forEach(function(element){
if($scope.processes.some(function(it) {return (it.name == element && it.checked== true) })) found = true;
});
return found;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myCtrl'>
<div ng-repeat="x in processes">
<input type="checkbox" ng-model="x.checked"/>{{x.name}}
</div>
<div ng-repeat = "y in toBeFiltered | filter: containFn">
<span class="title">{{y.Title}}</span>
<span class="process"> {{y.process}}</span>
</div>
</div>
run the snippet, if there is something isn't clear, or I didn't get feel free to comment
I have an object stored in $scope.addresscards inside a controller. The js is given below:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.addresscards = {
"work_address": {
"location":"workLoc",
"address": "workAddr",
"flat_no": "worknumber",
"landmark": "workLandmark"
},
"random1_address": {
"location":"someLoc",
"address": "SomeAddr",
"flat_no": "Somenumber",
"landmark": "someLandmark"
},
"home_address": {
"location":"homeLoc",
"address": "homeAddr",
"flat_no": "homenumber",
"landmark": "homeLandmark"
},
"random2_address": {
"location":"someLoc2",
"address": "SomeAddr2",
"flat_no": "Somenumber2",
"landmark": "someLandmark2"
}
};
}
I'm using ng-repeat to display the addresses. Here is the HTML:
<div ng-controller="MyCtrl">
<ul ng-repeat="(addressKey,addressVal) in addresscards">
<li>{{addressKey}} has :: {{addressVal.location}},{{addressVal.address}}, {{addressVal.location}}, {{addressVal.address}}</li>
</ul>
</div>
My output is:
home_address has :: homeLoc, homeAddr, homeLoc, homeAddr
random1_address has :: someLoc, SomeAddr, someLoc, SomeAddr
random2_address has :: someLoc2, SomeAddr2, someLoc2, SomeAddr2
work_address has :: workLoc, workAddr, workLoc, workAddr
I want to display the output such that, if the object has home_address it should be displayed 1st, then if the object has work_address it should be displayed. Then rest of the object should be showed alphabetically.
Here is expected result that I want to display:
home_address has :: homeLoc, homeAddr, homeLoc, homeAddr
work_address has :: workLoc, workAddr, workLoc, workAddr
random1_address has :: someLoc, SomeAddr, someLoc, SomeAddr
random2_address has :: someLoc2, SomeAddr2, someLoc2, SomeAddr2
I tried it using orderBy, It doesn't work on objects. How do I achieve this?
You can add a property to your address objects
$scope.addresscards = {
"work_address": {
"location":"workLoc",
"address": "workAddr",
"flat_no": "worknumber",
"landmark": "workLandmark",
"sort" : "2"
},
"random1_address": {
"location":"someLoc",
"address": "SomeAddr",
"flat_no": "Somenumber",
"landmark": "someLandmark"
},
"home_address": {
"location":"homeLoc",
"address": "homeAddr",
"flat_no": "homenumber",
"landmark": "homeLandmark",
"sort" : "1"
},
"random2_address": {
"location":"someLoc2",
"address": "SomeAddr2",
"flat_no": "Somenumber2",
"landmark": "someLandmark2"
}
};
and in your ng-repeat you can orderBy multiple fields first by sort to display home and work address first and then by address key for alphabetical order.
<ul ng-repeat="(addressKey,addressVal) in addresscards | orderBy:['sort','addressKey']">
<li>{{addressKey}} has :: {{addressVal.location}},{{addressVal.address}}, {{addressVal.location}}, {{addressVal.address}}</li>
</ul>
or in your controller you can sort all other addresses and append home and work address to the beginning of your list.
Plunker
I am trying to read the json data from a static json file that I have for testing on a local web server but I cannot get anything to show up with using the $http.get() service. I looked at a few other similar questions here but all accepted answers account for use of the promise methods, however on the angularjs v1.6.x+ these have been depreciated.
Initially I tried setting my json data on a variable inside of the controller, and everything worked fine, however once I moved to a JSON file nothing shows up. My first error was that I was unaware the JSON file has to be in ANSI format for the JSON.parse() angular calls to be able to work. Before switching the file encoding to ANSI I was getting syntax errors and my json structure was correct. (some text editor like Dreamweaver will create JSON files in UTF-8 format).
At this point when I inspect the webpage there are no JS errors on the console whatsoever, however no data shows up at all. Here is what I have:
My events.json
[
{
"day" : "Monday",
"objective" : "Pipeline",
"sessions" : [
{
"title" : "Leadership Excellence Luncheon",
"start" : "11:30am",
"end" : "1:00pm",
"location": "room A"
},
{
"title" : "Veteran Resume Workshop",
"start" : "1:15pm",
"end" : "2:00pm",
"location": "room B",
"speakers" : [
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/",
},
{
"name": "Jane Doe",
"title" : "VP",
"company": "Lancer",
"headshot" : "http://placehold.it/119x134.jpg",
}
]
}
]
},
{
"day" : "Tuesday",
"objective" : "Pipeline",
"sessions" : [
{
"title" : "Leadership Excellence Luncheon",
"start" : "11:30am",
"end" : "1:00pm",
"location": "room A"
},
{
"title" : "Veteran Resume Workshop",
"start" : "1:15pm",
"end" : "2:00pm",
"location": "room B",
"speakers" : [
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/",
},
{
"name": "Jane Doe",
"title" : "VP",
"company": "Lancer",
"headshot" : "http://placehold.it/119x134.jpg",
}
]
}
]
}
}
Here is my app.js
(function() {
var app = angular.module('Agendas',[]);
app.controller('TableController', ['$scope', '$http',
function($scope,$http) {
$scope.title = "test";
$scope.events = [];
$http({
method: 'POST',
url: 'http://localhost/ang/data/events.json',
}).then( function(response) {
$scope.events = response;
});
}]);
})();
Here is my index.html
<!doctype html>
<html>
<head>
.....
</head>
<body>
....
<div id="agenda" class="mainCont container-fluid well" ng-app="Agendas" ng-controller="TableController">
<div id="day" ng-repeat="event in events">
<h1>{{ event.day }} — {{ event.objective }}</h1>
<div id="sess" ng-repeat="session in event.sessions">
<div style="width: 140px; float: left; clear: left;">{{ session.start }} - {{ session.end }}<br><br><em>Location: {{ session.location }}</em></div> <div style="float: left;"><em>{{ session.title }}</em> <br>
<div class="panelist" ng-repeat="speaker in session.speakers"><img ng-src="{{ speaker.headshot }}"><br>
<a ng-href="{{ speaker.bio }}">{{ speaker.name }}</a><br>
{{ speaker.title }} <br>
{{ speaker.company }}</div>
</div>
</div>
<div class="aghr"></div>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
I noticed that your JSON file contains some errors. It could be related.
The ending tag should be one to close the array. ]instead of }.
The last field of a JSON object should not have a comma. E.g.:
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/", <--- remove comma
}
You can use a website as jsonlint to validate your JSON.
** As suggested, you might have to clear the browser cache first.
** Additionally change
$scope.events = response;
to
$scope.events = response.data;
I am reading the below json value from a module.js
.controller('home.person',['$scope','$filter','personResource',function($scope,$filter,personResource) {
$scope.searchPerson = function() {
var params = $scope.search || {};
params.skip=0;
params.take =10;
$scope.personDetails =
{
"apiversion": "0.1",
"code": 200,
"status": "OK",
"mydata": {
"myrecords": [
{
"models": [
{
"name": "Selva",
"dob": "10/10/1981"
}
],
"Address1": "ABC Street",
"Address2": "Apt 123",
"City": "NewCity1",
"State": "Georgia"
},
{
"models": [
{
"name": "Kumar",
"dob": "10/10/1982"
}
],
"Address1": "BCD Street",
"Address2": "Apt 345",
"City": "NewCity2",
"State": "Ohio",
"Country":"USA"
},
{
"models": [
{
"name": "Pranav",
"dob": "10/10/1983"
}
],
"Address1": "EFG Street",
"Address2": "Apt 678",
"City": "NewCity3",
"State": "NewYork",
"Country":"USA",
"Zipcode" :"123456"
}
]
}
}
}
}])
Now i am able to statically build the UX. But my each record set's key value pair count is different. So i want to build my html dynamically as per the current record set's count.Country & Zipcode is not exist in all records so i need to build dynamically the build and populate the html output.Most of the time, my json output is dynamic. Instead of persondetails, i may get the json output of a product details instead of PersonDetails.
<div ng-show="personDetails.mydata.myrecords.length > 0" ng-repeat="recordSingle in personDetails.mydata.myrecords">
<div >
<span >Address1: {{recordSingle.Address1}}</span>
<span >Address2: {{recordSingle.Address2}}</span>
<span>City: {{recordSingle.City}}</span>
<span>State: {{recordSingle.State}}</span>
<span>Country: {{recordSingle.Country}}</span>
<span>Zipcode: {{recordSingle.Zipcode}}</span>
</div>
</div>
One way is to use ng-if statement, for the optional span elements:
<span ng-if="recordSingle.Address1">Address1: {{recordSingle.Address1}}</span>
[Update #1: updated based on revised comments to question]
[Update #2: fixed typos in function and included plunkr]
I now understand that you want to dynamically build the display objects based on properties from the JSON object. In this case, I would iterate through the properties of the object. I would use a function to produce this array of properties for each object so that you can filter out any prototype chains. I would also remove out any unwanted propoerties, such as the internal $$hashKey and perhaps the array objects e.g.
In your controller:
$scope.getPropertyNames = getPropertyNames;
function getPropertyNames(obj) {
var props = [];
for (var key in obj) {
if (obj.hasOwnProperty(key) && !angular.isArray(obj[key]) && key !== '$$hashKey') {
props.push(key);
}
}
return props;
}
Then in your HTML view:
<div ng-repeat="record in personDetails.mydata.myrecords">
<div ng-repeat="prop in getPropertyNames(record)">
<span ng-bind="prop"></span>: <span ng-bind="record[prop]"></span>
</div>
</div>
This works for me... see this plunker. It is displaying each of the properties of the object in the array dynamically (you could have any property in the object). Is this not what you are trying to achieve?
I'm using Yeoman - angular generator.
JSBin: JSBin Link
I have a simple list of airports being set from a factory angApp.factory("Airports", function() {}); and displayed from ng-repeat <ul ng-repeat="airport in airports.detail">.
I would like to have an interaction that when each link is clicked it will match the airport code and display it in a new paragraph tag <p class="current">Current: {{currentAirport.name}}</p>.
Why wont the setAirport(airport.code) function set the currentAirport.name(or display?) when airport link is clicked in html?
Controller
angular.module("ang6App")
.controller("AirportsCtrl", function ($scope, Airports) {
$scope.formURL = "views/_form.html";
$scope.currentAirport = null;
$scope.airports = Airports;
$scope.setAirport = function(code) {
$scope.currentAirport = $scope.airports[code];
};
});
Factory Service in the same module
angApp.factory("Airports", function() {
var Airports = {};
Airports.detail = {
"PDX": {
"code": "PDX",
"name": "Portland International Airport",
"city": "Portland",
"destinations": [
"LAX",
"SFO"
]
},
"STL": {
"code": "STL",
"name": "Lambert-St. Louis International Airport",
"city": "St. Louis",
"destinations": [
"LAX",
"MKE"
]
},
"MCI": {
"code": "MCI",
"name": "Kansas City International Airport",
"city": "Kansas City",
"destinations": [
"LAX",
"DFW"
]
}
};
return Airports;
});
HTML
<div class="container" ng-controller="AirportsCtrl">
<ul ng-repeat="airport in airports.detail">
<li>{{airport.code}} -- {{airport.city}} </li>
</ul>
<p class="current"> current: {{currentAirport.name}}</p>
</div>
Your setAirport function should be written as:
$scope.setAirport = function (code) {
$scope.currentAirport = $scope.airports.detail[code];
};
But then, this could be simplified by passing the actual airport object directly:
<a href ng-click="setAirport(airport)">{{airport.code}}</a>
$scope.setAirport = function (airport) {
$scope.currentAirport = airport;
};