Show array data from ajax data in div using Angularjs - angularjs

I am using ajax to fetch the data from database. There are about 20 records in database. Here is the php code to fetch the data.
$query = "SELECT user_id,website,emailid FROM job_posting where uid = ? order by date DESC";
$result = $mysqli->prepare($query);
$result ->bind_param("i",$uid);
$result->execute();
$result->store_result();
$result->bind_result($user_id,$website,$emailid);
if($result->num_rows >0){
while ($result->fetch()) {
$website = $website;
$emailid = $emailid;
$user_id = $user_id;
$data['content'][] = array(
'website' => $website,
'emailid' => $emailid,
'user_id' => $user_id,
);
}
$data['success'] = 'true';
}
echo json_encode($data);
}
Above code is working fine. I can see the data in json format. Sample below.
{"content":[{"website":"test.com","emailid":"none#none.com","user_id":1},{"website":"test.com","emailid":"none#none.com","user_id":2},{"website":"test.com","emailid":"none#none.com","user_id":3}],"success":"true"}
Now I want to show this data by angular in webpage.
Angular code:
$http({
url: 'get_details.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
}
Please advise how to show the array data in a div.
<div class="col-md-12>
Need to show website, email id and user id in this div.
</div>

You should use then instead success . success and error have been deprecated and will be removed in v1.6.0.
$http({
url: 'get_details.php',
method: "GET",
params: {uid: uid}
})
.then(function(data) {
$scope.data = data.data.content
}
and in div
<div class="col-md-12 ng-repeat="x in data >
{{x.emailid}} - {{x.userid}}
</div>

It should be like this.(but its better use then function instead of success)
$http({
url: 'get_details.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
$scopemyData = data.content;
}
and in view
<div ng-repeat="data in myData">
<span>{{data.website}}</span>
<span>{{data.emailid}}</span>
<span>{{data.user_id}}</span>
</div>

Related

Angular JS with Laravel 5.3 search filter issue

I am developing a search filter using angular js and laravel 5.3.
My Angular JS:
$scope.search = function() {
var url = "bssrfilter1";
$http({
method: 'POST',
url: url,
data: $.param($scope.bssrfilter),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
$scope.bssrfilter = response;
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
My Laravel Controller:
public function filter(Request $request)
{
$search = $request->searchkey;
return $bssr = DB::table('adv')
->where('adv.description','like','%'.$search.'%')
->orWhere('adv.advtopic','like','%'.$search.'%')
->get()
->toArray();
}
My laravel route:
Route::post('/bssrfilter1', 'SiteController#filter');
When I submit the form for the first time it gives me correct search results. But after results are once displayed, submitting the search form again does not filter results. Any solution would be of great help.

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.

Angularjs refreshing after action same page

I'm trying to load a function on a link click, which works perfectly. Then angularjs does its magic until it arrives on the point where it shows the user feedback. I need to refresh the page after deleting an item, but it simply won't refresh.
Here's my href:
<a ng-click="deleteGroup(group.id)" target="_self">
<img src="img/deleteGroupIcon.png" width="45px"/></a>
here's my Controller:
$scope.deleteGroup = function ($groupId) {
$http({
method: 'POST',
url: apiUrl + 'group/delete',
data: {'groupId': $groupId}, // pass in data as strings
//headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// set the headers so angular passing info as
// form data (not request payload)
})
.success(function (data) {
if (!data.success) {
//$route.reload();
alert('groep is verwijderd');
} else {
$scope.group = data;
//$state.go('userDetail', {'user_id' : $userId});
}
});
};
and my html:
<div class="searchResults" ng-repeat="group in groups | searchForUser:searchString">
<div class="manageGroupWrapper">
<a class="normal" href="#">
<div class="newName h3">
{{group.title}}
</div>
<div class="newProfile">
<img ng-src="{{group.image}}" width="200px"/>
</div>
<div class="imageWrapper">
<a ui-sref="add_group" class="editGroupIcon"><img src="img/editGroupIcon.png" width="50px"/></a>
<a ng-click="deleteGroup(group.id)" target="_self"><img src="img/deleteGroupIcon.png" width="45px"/></a>
</div>
</a>
</div>
Your $scope.deleteGroup function should remove its target group from the $scope.groups so the content of the ng-repeat is automatically updated and does not display the group anymore.
$scope.deleteGroup = function (group) {
$http({
method: 'POST',
url: apiUrl + 'group/delete',
data: {'groupId': group.$groupId}, // pass in data as strings
//headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// set the headers so angular passing info as
// form data (not request payload)
}).success(function(data) {
$scope.groups.splice($scope.groups.indexOf(group));
});
};
To force refreshing the page with uiRouter you can use $state.go(target, params, {reload: true}).
$scope.deleteGroup = function (group) {
$http({
method: 'POST',
url: apiUrl + 'group/delete',
data: {'groupId': group.groupId}, // pass in data as strings
//headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// set the headers so angular passing info as
// form data (not request payload)
}).success(function(data) {
// This will reload the current state with the same stateParams
$state.go($state.current.name, $stateParams, {reload: true});
});
};

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)
}

Filter Array Using Angular

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>

Resources