Angularjs refreshing after action same page - angularjs

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

Related

Show array data from ajax data in div using 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>

AngularJS - How to wait for Google token before ajax call

I'm not sure how use a promise to wait for google to return a id_token. I would then make an ajax request using that token. Currently, it just immediately performs the ajax request before it has the token.
<script>
function onSignIn(googleUser) {
id_token = googleUser.getAuthResponse().id_token;
}
var app = angular.module('myApp', ['ngDialog']);
app.controller('directory_controller', function($scope, $q, $http, ngDialog) {
$http({
headers: { "Content-Type": "application/x-www-form-urlencoded" },
url: "my_ajax.php",
method: "POST",
data: "gtoken=" + id_token
})
.then(function successCallback(response) {
console.log("success");
console.log(response);
}),
function(response) {
console.log("failure");
console.log(response);
}
});
</script>
<div ng-app='myApp'>
<div ng-controller='directory_controller'>
</div>
</div>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>

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 - ng-repeat - using parent repeat data in child http request

I have what would seem to be a simple problem with AngularJS - apologies if so. I'm new and have searched all over and can't quite find an answer to what I want to do.
Basically I have a $http request that is getting a list of 'Cards' from a server which I'm then using ng-repeat to build in the HTML. I then want to populate those Cards with a number of 'Metrics' - also retrieved from the server. I have a controller for the 'Cards' (parents) and a separate controller for the 'Metrics' (children).
My issue is that I can't work out how to reference the ID of the parent 'Card' when making the child $http request.
Below is the HTML & JS that I am using - any help would be appriciated:
HTML:
<div class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
<div ng-repeat="Card in Dashboard.DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric">
<div ng-repeat="Metric in Metric.DashboardMetrics">
{{Metric.MetricDisplayName}}
</div>
</div>
</div>
</div>
JS:
(function () {
var app = angular.module('OtterDashboard', [ ]);
app.controller('DahsboardCardController', [ '$http', function($http) {
//Declare a varaible for the data
var DashboardCards = this;
//Set the varaiable to an empty array to receive the data
DashboardCards.DashboardCards = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardCards.DashboardCards = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card) {
//Declare a varaible for the data
var DashboardMetrics = this;
//Set the varaiable to an empty array to receive the data
DashboardMetrics.DashboardMetrics = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + **???reference to parent card ID???** + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Metric data could not be retrieved');
});
}]);
})();
Thank you!
EDIT 1
Use a service for shared variable between controllers. Look the example:
app.controller('DahsboardCardController', ['$http', function($http, $sharedResource) {
var DashboardCards = this;
DashboardCards.DashboardCards = [ ];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardCards.DashboardCards = data.data.d.results;
$sharedResource.set("id", "<pass id value>");
}, function errorCallback(response) {
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card, $sharedResource) {
var DashboardMetrics = this;
DashboardMetrics.DashboardMetrics = [];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + $sharedResource.get("id") + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
console.log('Metric data could not be retrieved');
});
}]);
app.factory('$sharedResource', function () {
var property = {};
return {
get: function (key) {
return property[key];
},
set: function(key, value) {
property[key] = value;
}
};
});
EDIT 2
When working with angularjs is recomended use a one object for print object in table. Why this is a beautiful s2.
Look this example. To help you in development. Use the sample function pass the parentId in load(CardId). This function will run in the page load.
I too fix code html. You used the alias controller before input field of same.
var app = angular.module("App", []);
app.controller('DahsboardCardController', ['$scope', function($scope) {
$scope.DashboardCards = [{
CardId: "111",
CardDisplayName: "Card 1"
}, {
CardId: "222",
CardDisplayName: "Card 2"
}, {
CardId: "333",
CardDisplayName: "Card 3"
}];
}
]);
app.controller('DahsboardMetricController', ['$scope', function($scope) {
$scope.load = function(CardIdParent) {
console.log(CardIdParent);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
{{Dashboard.DashboardCards}}
<div ng-repeat="Card in DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric" ng-init="load(Card.CardId)">
This a id parent: {{Card.CardId}}
<div ng-repeat="MetricItem in DashboardMetrics">
{{MetricItem.MetricDisplayName}}
</div>
</div>
</div>
</div>
</div>

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