Filter Array Using Angular - angularjs

I am trying to filter an array (courses) by a property, FacilityId.
I am getting a response back for all of my $http calls in my controller which is as follows:
function holeIndexController($scope, $http) {
$scope.facilities = [];
$scope.courses = [];
$scope.holes = [];
getFacilities();
getCourses();
getHoles();
function getFacilities() {
$http({
method: 'GET',
url: '/api/facility'
}).
success(function(result) {
$scope.facilities = result;
}).error(function () {
console.log("Error: " + result.ExceptionMessage);
alert("Could not load facilities");
});
}
$scope.courseByFacility = function (facilities) {
return function(courses) {
return course.facilityId === facility.facilityId;
};
};
function getCourses() {
$http({
method: 'GET',
url: '/api/course'
}).
success(function (result) {
$scope.courses = result;
}).error(function (result) {
console.log("Error: " + result.ExceptionMessage);
alert("Could not load courses");
});
}
function getHoles() {
$http({
method: 'GET',
url: '/api/hole'
}).
success(function(result) {
getFacilities();
$scope.holes = result;
}).error(function(result) {
console.log("Error: " + result.ExceptionMessage);
alert("Could not load courses");
});
}
}
And my HTML is as follows:
<div data-ng-repeat="f in facilities">
Facility: {{f.Name}}
<div data-ng-repeat="c in courses | filter: coursesByFacility">
Course: {{c.Name}}
</div>
</div>
What is the best way to filter courses by their respective FacilityId's?

Pass the facility into the filter function, like:
<div ng-repeat="c in courses | filter:coursesByFacility(f)">
Also, your coursesByFacility function takes a courses parameter, but then you're trying to act upon course (no s). Change this to this:
$scope.coursesByFacility = function(facility) {
return function(course) {
return course.facilityId === facility.facilityId;
}
}
See this jsbin
Edit: Didn't realize the jsbin link was going to strip all the code so you can't see it. Anyways, just view the source, it's minimal and easy to read

You could create a function called getCoursesByFacility() which has a facilityId parameter. The function should iterate through the list of courses and build an array of courses with that facilityId, then return the list. You would then need to call the function from your javascript. Something like this should work:
<div data-ng-repeat="f in facilities">
Facility: {{f.Name}}
<div data-ng-repeat="c in getCoursesByFacility(f.facilityId)">
Course: {{c.Name}}
</div>
</div>

Related

How to populate md-autocomplete dropdown list?

I'm trying use md-autocomplete with $http(), I can see the values in the console, but I can't display the data returned from the api request to the autocomplete.
I tried using the return keyword to return values stored in the JSON array.
<md-autocomplete
md-autoselect=true
placeholder="Search for films"
md-items="item in querySearch(searchText)"
md-item-text="item.title"
md-min-length="2"
md-search-text="searchText"
md-selected-item="selectedItem">
<md-item-template>
<span class="films-title">
<span md-highlight-flags="^i" md-highlight-text="searchText">
{{item.title}}
</span>
</span>
</md-item-template>
<md-not-found>
No match found.
</md-not-found>
</md-autocomplete>
The data I want to display is stored in a JSON array and the contents can be seen in the console:
'use strict';
filmApp.controller('SearchController',function ($scope, $http){
$scope.results = {
values: []
};
$scope.querySearch = function (query) {
$http({
url: 'https://api.themoviedb.org/3/search/movie?include_adult=false&page=1',
method: 'GET',
params: {
'query': query,
'api_key': apiKey
}
}).success(function (data, status) {
for (var i = 0; i < data.results.length; i++) {
$scope.results.values.push({title: data.results[i].original_title});
console.log($scope.results.values);
return $scope.results.values;
}
console.log("STATUS: "+status);
}).error(function (error) {
console.log("ERROR: "+error);
});
};
});
querySearch method should return a promise & from the promise.then you should be returning a data. So in your case you used .success/.error callbacks(thought they are already deprecated) which is disallow promise to be return from your querySearch method
$scope.querySearch = function (query) {
return $http.get('https://api.themoviedb.org/3/search/movie?include_adult=false&page=1', {
params: {
'query': query,
'api_key': apiKey
}
}).then(function (data, status) {
var data= response.data;
for (var i = 0; i < data.results.length; i++) {
$scope.results.values.push({title: data.results[i].original_title});
console.log($scope.results.values);
}
return $scope.results.values;
})
};

AngularJS pushing/updating new data (likes/dislikes) to API using PUT

I am trying to create an app that counts likes for beer! This would updates the API the beers are stored on and in turn update the number of likes on the API and angularJS view using the PUT method. I am able to get the view to work correctly increasing every time the like is clicked. I am unsure why my PUT method continues to return a 404 and will not update the API. please see code below for my put method. I have also included my JS and HTML for this. I feel like I am close but cannot figure out how to get the "likes" to update on the API. Thank you in advance!! I think i am passing incorrect data to the PUT method.
HTML:
<div ng-app="beerApp" ng-controller="BeerController" class="jumbotron">
<div class="all-beer">
<div class="single-beer" ng-repeat="beer in allBeer">
<div>{{beer.name}}</div>
<div>{{beer.likes}}</div>
<button ng-click="decrease(beer)">X</button>
<button ng-click="increase(beer)">\3</button>
</div>
</div>
</div>
JS:
angular.module('beerApp', []).controller('BeerController', function($scope, $http) {
$scope.allBeer = [];
$scope.beerSum = function() {
$http({
method: 'GET',
url: /api/beers
}).
then( function(response) {
if(typeof response === 'object') {
var dataArr = response.data;
for (var i = 0; i < dataArr.length; i++) {
var beer = dataArr[i];
$scope.allBeer.push(beer);
}
} else {
return;
}
}, function(error) {
console.log('i am an error', error);
})
};
$scope.beerSum();
$scope.increase = function(beer){
var newLikes = beer.likes++;
$http({
method: 'PUT',
url: '/api/beer/',
data: JSON.stringify($scope.allBeer.likes),
}).then(function successCallback(response) {
console.log("Updated!");
}, function errorCallback(response) {
console.log("not updated")
});
};
First things first you are missing some syntax for the http api's. Secondly you are calling a property on an array that doesn't exist. Thirdly your api won't work because of the logic that you have. You have an array of beers and you want to increase the likes on a single beer. Create a method on the server that accepts a beer, the server will take that beer and increase it's likes by 1, then save to the database or whatever.
Depending on the server you are using you have two options.
You can define a command simply at /api/beers and configure the server to accept an object and use that objects id for the server update. If this is the case I recommend creating this endpoint, /api/beers/update and make it a POST, and pass it the object, then within this command do all your update logic.
Or for example the Microsoft Web Api the default put (update) endpoint looks like so, public void Update(int id, object data){} with a url of /api/beers/{id}. To use this method you need to change the code for the updateLikes method I wrote.
See Below:
$scope.updateLikes = function(beer, likeCount){
beer.likes+= likeCount;
$http({
method: 'PUT',
url: '/api/beer/' + beer.id,
data: JSON.stringify(beer),
}).then(function successCallback(response) {
console.log("Updated!");
//Trigger reload of data
$scope.beerSum();
}, function errorCallback(response) {
console.log("not updated")
});
};
Extra Help
If you are still having trouble and are working in a GitHub environment I would gladly help you with your code more directly. Other than that the answer I have posted answer's your question, and does so in what I believe to be good coding practices for AngularJS. With one minor exception there code be a changes to the line that reads, beer.likes += likeCount because this also updates the original beer object. I suppose that is preference, but please contact me if you need more help.
JS:
angular.module('beerApp', []).controller('BeerController', function($scope, $http) {
$scope.allBeer = [];
$scope.beerSum = function() {
$http({
method: 'GET',
url: '/api/beers' //<-- Added string opening and closing tags
}).
then( function(response) {
if(typeof response === 'object') {
var dataArr = response.data;
for (var i = 0; i < dataArr.length; i++) {
var beer = dataArr[i];
$scope.allBeer.push(beer);
}
} else {
return;
}
}, function(error) {
console.log('i am an error', error);
})
};
$scope.beerSum();
$scope.increase = function(beer){
var newLikes = beer.likes++;
//Your code
$http({
method: 'PUT',
url: '/api/beer/', //<-- closing
data: JSON.stringify($scope.allBeer.likes), //<-- Where does likes come from? $scope.allBeer is an array of beer but the array itself doesn't have a property called likes.
}).then(function successCallback(response) {
console.log("Updated!");
}, function errorCallback(response) {
console.log("not updated")
});
//End your code
//My Code
beer.likes+=1; //<-- My bad I fixed this.
$http({
method: 'PUT',
url: '/api/beer/', //<-- closing
data: JSON.stringify(beer), //<-- The object you passed into the function
}).then(function successCallback(response) {
console.log("Updated!");
}, function errorCallback(response) {
console.log("not updated")
});
//End my code
};
Possible problems
Your api doesn't work with put, in which case this question isn't the correct one.
Something else is internally wrong with your program, but from this point on I think you're looking at something wrong with your api, whatever that may be.
angular.module('beerApp', []).controller('BeerController', function($scope, $http) {
$scope.allBeer = [];
$scope.beerSum = function() {
$scope.allBeer.push({
"name": "Miller Lite",
"likes": 0
});
$http({
method: 'GET',
url: '/api/beers' //<-- Added string opening and closing tags
}).
then( function(response) {
if(typeof response === 'object') {
var dataArr = response.data;
for (var i = 0; i < dataArr.length; i++) {
var beer = dataArr[i];
$scope.allBeer.push(beer);
}
}
}, function(error) {
console.log('i am an error', error);
})
};
$scope.beerSum();
$scope.updateLikes = function(beer, likeCount){
beer.likes+= likeCount;
$http({
method: 'PUT',
url: '/api/beer/',
data: JSON.stringify(beer),
}).then(function successCallback(response) {
console.log("Updated!");
//Trigger reload of data
$scope.beerSum();
}, function errorCallback(response) {
console.log("not updated")
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="beerApp" ng-controller="BeerController" class="jumbotron">
<h1>Beers on Tap</h1>
<div class="all-beer">
<div class="single-beer" ng-repeat="beer in allBeer">
<div>{{beer.name}}</div>
<div>{{beer.likes}}</div>
<button ng-click="updateLikes(beer, -1)">Down Vote</button>
<button ng-click="updateLikes(beer, 1)">Up Vote</button>
</div>
</div>
</div>
</body>
</html>

How to perform an ajax lookup within `ng-repeat`

I have an ng-repeat of employees. One of the result fields returned is an employee number e.g. "12345".
How can I perform an ajax lookup and replace the employee number with the corresponding name?
Example: /_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '12345'
would return: "Doe, John".
I've tried using a filter but nothing ever gets displayed even though I can see results returned.
<div ng-repeat="emp in employees"">
<i class="fa fa-user"></i> {{emp.id}}
</div>
app.filter('getName', function($http) {
return function(id){
if (id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data, status, headers, config) {
userInfo = data.d.results[0].pn;
console.log(userInfo);
}).error(function (data, status, headers, config) {
userInfo = "0";
});
return userInfo;
}
};
});
The filter function is synchronous, while the $http call is asynchronous. The success callback isn't even going to be executed until after the filter function has already returned, so it looks like the return value will be undefined.
An angular filter isn't really appropriate for loading data from an API, and there's an easier approach. Add userInfo to the employees array in the appropriate service/factory/controller (that's up to how you're organizing your code, but the controller where you set $scope.employees is the quick and dirty option). Something like a forEach through the array making an API call for each one and setting employee.userInfo in the success callback:
app.controller('EmployeeController', function($scope, $http) {
// $scope.employees is initialized somehow
$scope.employees.forEach(function (employee) {
if (employee.id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+employee.id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data) {
employee.userInfo = data.d.results[0].pn;
}).error(function () {
employee.userInfo = "0";
});
}
});
});
And in your template:
<div ng-repeat="emp in employees">
<i class="fa fa-user"></i> {{emp.userInfo}}
</div>
It's up to you to figure out what to do before the ajax request is finished, while emp.userInfo is undefined - hide the element, show a placeholder, etc.

Display attribute of ngrepeat from ngcontroller alias

Without the ngcontroller alias, I can fetch the data. However, when with alias, I can't. What is my mistake here?
HTML tags:
<div style="padding: 10px" id="content_dv" ng-controller="displaytopic_ctrl as f">
<div class="topic_dv" ng-repeat="t in f.topic">
<p>{{ t.MEMBER_NAME }}</p>
</div>
</div>
in app.js:
.controller('displaytopic_ctrl', ['$http', function($http) {
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d){
if(d.t=='p'){
this.topic = d.topic;
}
}).error(
function(){
console.log('Query error');
});
}]);
Due to the way JavaScript closures work, the this variable that you are using in your success callback is not the controller. The most commonly used mechanism to solve this is to create an alias for the controller which you can reference inside your callbacks.
For Example:
.controller('displaytopic_ctrl', ['$http',
function($http) {
var controller = this;
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d) {
if (d.t == 'p') {
controller.topic = d.topic;
}
}).error(
function() {
console.log('Query error');
});
}
]);

Delete record using angular

PROBLEM
Hello! I want to delete record using angular. So that must look like that: I click button "X" (delete) and record must be deleted.
WHAT I GOT FOR NOW
I don't know if all is correct, but there is my code:
html
<div ng-repeat="lists in listsdata.lists">
<div id="DIV_24" close-on-outside-click="div.popup_information">
<button ng-click="lists.show = !lists.show" id="MORE_BUTTON">:</button>
<div class="popup_information" ng-show="lists.show">
<button id="DELETE_BUTTON" ng-click="del_list()">X</button>
<a href="">
<button id="EDIT_BUTTON">E</button>
</a>
</div>
<a href="#/{{lists.id}}">
<div id="DIV_25">
{{lists.name}}
</div>
<div id="DIV_26">
</div>
</div></a>
</div>
angular
myApp.controller('listsController', ['$scope', '$log', '$http',
function($scope, $log, $http){
$http({
method: 'GET',
url: 'http://localhost/anydocopy/public/lists'
})
.success(function (d) {
console.log(d);
$scope.listsdata = d;
});
$scope.key = function($event){
console.log($event.keyCode);
if ($event.keyCode == 13) {
var list = {
name: $scope.listname
};
$scope.listname = '';
$http({
method: 'POST',
url: 'http://localhost/anydocopy/public/lists',
data: list
})
.success(function () {
console.log('true');
$http({
method: 'GET',
url: 'http://localhost/anydocopy/public/lists'
})
.success(function (d) {
console.log(d);
$scope.listsdata = d;
});
})
.error(function () {
console.log('false');
});
}};
$scope.del_list = function () {
$http({
method: 'DELETE',
url: 'http://localhost/anydocopy/public/lists/'+ $scope.listsdata.lists.id
});
console.log($scope.listsdata.lists)
}
}]);
laravel controller
public function delete($id)
{
$response['lists'] = Lists::findorfail($id)->delete();
return Response($response, 201);
}
laravel route
Route::delete('lists/{id}', 'ListsController#delete');
So for now when I click button, I cant set right url in agular function, because I can't get that id from $scope.listsdata.. I can get all array, but how to get only id I want? So if I click on button what is on list with id=1 so in angular function must work like method=delete and url= url+id. How to do that, please help.
Pass what you want to delete as argument. And rename lists to list, since it represents a single list:
<div ng-repeat="list in listsdata.lists">
...
<button ng-click="del_list(list)">X</button>
and
$scope.del_list = function(listToDelete) {
$http({
method: 'DELETE',
url: 'http://localhost/anydocopy/public/lists/'+ listToDelete.id
});
}
Pass argument in ng-click function you want to delete like
<div ng-repeat="list in listsdata.lists">
...
<button ng-click="del_list(list)">X</button>
</div>
you Delete function looks ike
$scope.del_list = function(selectedItem) {
$http({
method: 'DELETE',
url: 'http://localhost/anydocopy/public/lists/'+ selectedItem.id
});
console.log($scope.listsdata.lists)
}

Resources