I have script that work on button click:
$scope.ShowDetailsAboutTicket = function (pinTicket) {
if ($scope.showdetail == false && pinTicket != null) {
$scope.pinTicket = pinTicket;
$http.get(TicketUrl + 'GetTicket/' + $scope.terminalId + '/' + $scope.pinTicket)
.success(function(data, status, headers, config)
{
$("#background").addClass("darker");
$scope.showdetail = true;
$scope.ticketNotFound = false;
$location.search("ticketid", pinTicket);
})
.error(function(data, status, headers, config) {
$scope.ticketNotFound = true;
$scope.showdetail = false;
})
.then(TicketDetails, ErrorResponse);
}
}
Everything works fine.I get url :http://localhost:60664/Home#?ticketid=8837278738 but i want when user click on button that redirect him to Sport page with those parameters...how can i do that? I tried with window.location but i dont get parameters
You should define routes in your configuration and then you should invoke that route when a user clicks your button.
You can use either ng-route or the more extended version ui-router.
You can use $routeParams for this
Something like this:
Module.controller("yourControler", ["$routeParams", function($routeParams){
//do whatever you need with the controller
$scope.ticketId = $routeParams.ticketId;
$scope.dosomethingOnSubmit = function() {
//read $routeParams.ticketId and use $location to redirect user where you need to (but that will result in GET action)
//Or you can perform your own POST request via $http service or $resource
//Read the docs :)
}
}]);
Then in your template you reference the ticketId
<a class="myButton" ng-href="some/path/?ticketId={{ticketId}}">Go to Sport page</a>
Ok, if that is submit button, then you can do this
<form ng-submit="dosomethingOnSubmit()">
<button type="submit">Submit</button>
</form>
ngSubmit - https://docs.angularjs.org/api/ng/directive/ngSubmit
$http - https://docs.angularjs.org/api/ng/service/$http
Related
Here's the rundown. Users can view a razor page both anonymously and logged in. If they are logged in, they get certain features. In my controller, I have a boolean isAnonymous which I set to true or false depending on if there's a signed in user or not. I pass isAnonymous to my view model which gets sent to the razor page.
In the razor page, I have a javascript script tag which needs to retrieve that boolean value and, if isAnonymous is false (meaning someone is signed in), fire off one of two ajax calls to the server.
The first thing I do in my script tag is get the isAnonymous value and convert it to a JavaScript boolean with this:
var isAnonymous = #Json.Encode(Model.IsAnonymous);
after console logging, this appears to return correctly.
Then i put in my if statement. The summary here is if the user is not logged in, none of these functions nested inside the if statement should fire, because they take an ApplicationUser as part of the model. If there is no signed in user, Model.User is null and throws a Null Reference Exception. I thought putting my ajax calls inside the if statement would guard against the exception, but the the logic seems to be blowing right through the if (isAnonymous == false) and hitting those functions despite the logic. Any thoughts as to why this is happening? When isAnonymous is true, I can't have the functions fire.
if (isAnonymous == false) {
if ($('.bookmark-btn').hasClass('bookmark-story-btn')) {
addBookmark();
} else {
removeBookmark();
}
function addBookmark() {
//bookmark a story btn click event
$('.bookmark-story-btn').on('click', function () {
var storyid;
//the storyid should come as a string -
//try to parse it as an int for the controller
if (!isNaN($(this).attr('storyid'))) {
storyid = parseInt($(this).attr('storyid'))
//verify successful conversion from string to int before ajax call
if (typeof (storyid) == 'number') {
var userid = $(this).attr('userId')
var newBookmark = {
UserId: userid,
StoryId: storyid,
};
$.ajax({
url: "/api/bookmark/new",
method: "POST",
data: newBookmark,
success: function (data) {
//remove the save bookmark btn and dynamically add
//the remove bookmark btn so
//the page doesn't require a refresh
$('.bookmark-story-btn').remove();
$('.bookmark-btn-group').append("<button bookmarkId='"
+ data.Id
+ "' userId=#Model.User.Id storyId=#Model.StoryId"
+" class='btn remove-bookmark-btn bookmark-btn'>"
+"<i class='fas fa-2x fa-bookmark'></i></button>")
removeBookmark();
},
error: function (error) {
$('.page-alert').css('visibility', 'visible')
.html("Whoops. Something went wrong."
+" Adding the bookmark failed.")
//automatically close the alert-danger div
//after 2 seconds
setTimeout(function () {
$('.page-alert').css('visibility', 'hidden')
}, 3000);
}
});
}
}
});
}
function removeBookmark() {
//remove a bookmark click event
$('.remove-bookmark-btn').on('click', function () {
if (!isNaN($(this).attr('bookmarkid'))) {
bookmarkid = parseInt($(this).attr('bookmarkid'))
//verify successful conversion from string to int before ajax call
if (typeof (bookmarkid) == 'number') {
//call the ajax
$.ajax({
url: "/api/bookmark/" + bookmarkid,
method: "DELETE",
success: function (data) {
//show-hide the appropriate icons
$('.remove-bookmark-btn').remove();
$('.bookmark-btn-group').append("<button userId=#Model.User.Id"
+" storyId=#Model.StoryId class='btn bookmark-story-btn"
+" bookmark-btn'><i class='far fa-2x fa-bookmark'>"
+"</i></button>")
addBookmark();
},
error: function (error) {
$('.page-alert').css('visibility', 'visible')
.html("Whoops. Something went wrong here."
+" Removing the bookmark didn't work.")
//automatically close the alert-danger div
//after 2 seconds
setTimeout(function () {
$('.page-alert').css('visibility', 'hidden')
}, 3000);
}
})
}
}
})
}
}
You can use Request.IsAuthenticated in both the Razor view:
#if(Request.IsAuthenticated)
{
<script>
' your authenticated client side script here
</script>
}
And then check again server side when posting in your controller for example:
public ActionResult Index()
{
if(Request.IsAuthenticated)
{
//server logic here
}
}
Better still if you decorate the method with the AuthoriseAttribute the user will get an 403 Unauthorized.
You can then do something similar server side for the UserId:
[Authorize]
public ActionResult Index()
{
var userId = User.Identity.Name;
}
Then you don't even need to pass the UserId about. This is all based on using the common Identity practices:
https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/introduction-to-aspnet-identity
I am calling a Web Service which returns around 3000 records as data entries as HTML response & i am trying to read this response using angularJS.
Below is my AngularJS code i am using to call the service
angular.module('tabApp', ['ngSanitize'])
.controller('TabController', ['$scope', 'HttpService', function($scope, HttpService) {
$scope.tab = 0;
$scope.setTab = function(newTab){
$scope.tab = newTab;
$scope.loading = true;
HttpService.CallService('Service.php?id='+newTab,newTab, function (data) {
$scope.myText = data;
$('.count').show();
$("[id^=searchg]").show();
$('.results').show();
});
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
$scope.setTab1 = function(newTab1){
$scope.tab = newTab1;
$('.loaderImage').hide();
};
$scope.isSet1 = function(tabNum){
return $scope.tab === tabNum;
};
}])
.service('HttpService', ['$rootScope', '$http', function ($rootScope, $http) {
$rootScope.loading = true;
return {
CallService: function (url,tabnum, callback) {
$http({
method: "POST",
url: url,
data: {id: tabnum}})
.success(function (data, status) {
$('.loaderImage').hide();
callback(data, status);
}).error(function (data, status) {
$('.loaderImage').hide();
callback(status);
});
}
}
}]);
My problem is the browser hangs if the returned records are more than 1500. Please advise on how i can improve this.
Update:
My html code looks like this
<div ng-show="isSet(1)">
<div id=matches style="display:none"></div>
<input type=text id=searchg placeholder="Type to search..." style="display:none" />
<p class="preload" ng-bind-html="myText"></p>
</div>
As we can see it is the bulky data which you are trying to bind. In Future, it could be more bulky.
You should use the server side pagination and get only the number of records, what your pagination is.
Here is the JSFiddle link for the reference.
http://jsfiddle.net/dwahlin/3Kewg/
Hope this helps! CHEERS TO CODE! :)
As #Mohit Dixit suggested, you should prefer to do server side paging and request only active page records.
I would advise you to use smart table library for this. Here is the official website for same. They support paging(both server side and client side), filter and sorting in one go.
Please note that there are many library available for this purpose but I am suggesting this as I am using it from past few years.
I have a trouble with IE when ng-click is used in the button.
I want to reload the data from spring controller whenever user click on the button which is working fine in chrome but not in IE11.
Issue is when page is loaded data is displayed on the webpage, when Refresh Data button is clicked, it will reload the data by hitting to the spring controller which is not working in IE. In IE, when user click on a button, it is hitting the angular controller as well as service method also but not hitting the spring controller.But when developer tools is opened it is hitting the spring controller.
Example below:
html code:
<div ng-controller="loadingSampleCtrl">
<button class="btn btn-primary" type="button" ng-click="loadOrRefreshData()">Reload</button>
{{myData.empName}} /* This is printed in chrome as well as in IE with developer tools opened*/
</div>
js code:
myApp.controller('loadingSampleCtrl', function ($scope, MyService) {
$scope.loadData = function () {
$scope.loading = true;
MyService.testData().then(
function (response) {
alert("response back from spring controllerf");
if(window.navigator.msSaveOrOpenBlob){
$scope.IEBrowser = true;
$scope.myData = response;
/* $timeout(function() {
$scope.pdfName = response;
}, 0);*/
} else {
$scope.IEBrowser = false;
$scope.myData = response;
}
},
function (errResponse) {
$rootScope.showError("Internal error" + errResponse);
});
}
$scope.testData();
});
//service call
_myService.testData = function(){
alert("service call");//this alert is visible in IE
var deferred = $q.defer();
var repUrl = myAppURL+'/myDataToRead/getData.form';
$http.get(repUrl).then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
deferred.reject(errResponse);
}
);
return deferred.promise;
}
spring controller:
#RequestMapping(value = "/getData", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
List<String> getMyData(HttpServletRequest request) throws Exception {
System.out.println("In MyDataController"); //not printed in IE when tested without developer tools
//logic here
//return statement
}
Any suggestions would be helpful.
i check you url var repUrl = yAppURL+'/myDataToRead/getData.form';, and i this the issue is you are not map controller with the path. you are only map your method with /getData. you need to use #RequestMapping annotation into your controller. you can refer below code :
#RestController
#RequestMapping("/myDataToRead")
I am learning how to use angular javascript alongside my favorite, PHP framework (CodeIgniter). I have a login section that authenticates to a service and gets the response using angular js. The code works fine. See snippet below
var login = angular.module('authenticationApp' , ['ngMaterial' , 'ngRoute']) ;
login.controller('authenticationController', function ($scope, $http) {
$scope.authenticate = function () {
if ($scope.username == undefined || $scope.password == undefined) {
$scope.login_error_message = "All form fields are required" ;
} else {
var url = get_base_url() + 'student/authentication/login?username=' + $scope.username + '&password=' + $scope.password ;
$http.post(url).then(
function (response) {
console.log(response) ;
/*Here I handle success*/
}, function (response) {
$scope.login_error_message = "Service Error!. Response: " + response ;
}
) ;
}
} ;
My problem is how can I send that response to the success.php page and also redirect to the success page. I can redirect using
window.location.href = get_base_url() + 'administrator/authentication/dashboard' ;
My challenge now is actually sending the response to this new location.
Thanks in advance and I am ready to provide more details if need be
After battling for long, I just decided to use plain js. Crappy but works.
So, i'm using AngularJS with X-Editable to make an easier way to edit my data.
I have a table with all the information of a client such as name, phone, address, etc.. And I could apply X-Editablejust fine until the moment I need to actually save the edit on the database.
Also, this page just show one single client, is an individual client page, with only his details.
This is the code I'm using:
page.html
<table fixed-header class="detcli_table" ng-init="get_detcliente()">
<thead>
<tr>
<th>Campo</th>
<th>Informação</th>
</tr>
</thead>
<tbody>
<tr>
<td>Código</td>
<td>{{cliente.id}}</td>
</tr>
<tr>
<td>Nome</td>
<td><span editable-text="cliente.nm_cliente" onaftersave="updatePerson(cliente.nm_cliente)">{{cliente.nm_cliente || "Empty"}}</span></td>
</tr>
<tr>
<td>Tel.</td>
<td><span editable-text="cliente.num_tel" onaftersave="updatePerson(cliente.num_tel)">{{cliente.num_tel || "Empty"}}</span></td>
</tr>
[... more code ...]
</tbody>
</table>
app.js
myApp.controller('DetClientesCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
var clienteId = $routeParams.id;
$scope.get_detcliente = function() {
var url = 'scripts/php/db.php?action=get_cliente';
return $http.get(url).success(httpSuccess).error(function() {
alert("Oops, erro!");
});
}
httpSuccess = function(response) {
$scope.detRes = response;
}
function getById(arr, id) {
for (var d = 0, len = arr.length; d < len; d += 1) {
if (arr[d].id === id) {
return arr[d];
}
}
}
$scope.get_detcliente().then(function(){
$scope.cliente = getById($scope.detRes,$routeParams.id);
});
//Update Client
$scope.updatePerson = function() {
$http.post('scripts/php/db.php?action=upd_cliente',
{
'id': $routeParams.id,
'nm_cliente' : $scope.nm_cliente,
'num_tel' : $scope.num_tel
}
).success(function (data, status, headers, config) {
$scope.get_detcliente();
console.log("efeutou o post!");
}).error(function (data, status, headers, config) {
console.log("Algo deu errado!");
});
};
}]);
control.php
This is the method i'm using to add new data, delete and, in this case, to update an existing data
function upd_cliente() {
$data = json_decode(file_get_contents("php://input"));
$id = $data->id;
$nm_cliente = $data->nm_cliente;
$num_tel = $data->num_tel;
$qry = "update cad_cliente set nm_cliente = '$nm_cliente', num_tel = '$num_tel' where cd = '$id'";
}
When I run the code, I get no errors at all. The console.log I'm using is showing properly in the console, the editing I do, is working fine on the screen but when I refresh the page, there is no data saved, it goes back to the previous data.
What may be wrong?
And also I don't know if this is the best way to do it, since I have a table with about 10 to 15 lines of information, so if I edit just 1 or 5 lines, the code will have to run for each edit I make.
Is there a better way to process it?
Well, after some research and a lot of try/fail i cam up with the solution.
in the page page.html i needed to remove the remove the code inside the (), so it is going to be like this:
page.html
<td><span editable-text="cliente.nm_cliente" onaftersave="updatePerson()">{{cliente.nm_cliente || "Empty"}}</span></td>
And on the app.js i needed to use $scope.cliente.nm_cliente instead of $scope.nm_cliente. So the code will be like this:
app.js
$scope.updatePerson = function() {
$http.post('scripts/php/db.php?action=upd_cliente',
{
'id': $routeParams.id,
'nm_cliente' : $scope.cliente.nm_cliente,
'num_tel' : $scope.cliente.num_tel
}
).success(function (data, status, headers, config) {
//Success code here
}).error(function (data, status, headers, config) {
//Error code here
});
};
Then, on the php file i just need to write the other fields i need to update on the database, in my case, it will be more than 15 fields to be possible to update.
Note: As far as i know, this code only works with the option onaftersave="" because if we use the option onbeforesave="", like the name itself, the data will not be passed since it's being executed before the new data is passed to the $scope.
I'm sorry if any of my information is wrong, i'm starting learning AngularJS right now. But this is working for me.
Also, i don't know if there is a better way to achieve this result, so, if anyone knows, please share it with us!