Rendering order in angular - javascript

I'm trying to get rid of a visual issue I got.
I have a ng-repeat displaying some stuff and a footer on my page.
The ng-repeat taking some time to display, I see the footer n my page before anything else and that is disturbing.
How can I force the footer to display only when something else like an ng-repeat has finish rendering on the page ?

ng-repeat is rendered with a list of value; that you propably get from a WebService.
add a $rootScope.myBool that is false at app start.
Update that valueto true within your $http call (or way to fill your ng-repeat array)
once your array is completed add a ng-show="myBool" to your footer to
prevent it from showing before your array is filled

It always better to create one service which shows loader icon full width when any ajax call or data loading is happening.
this is very normal scenario with angularJs SPA, that the page look distorted or footer coming first at page level, so better create one service which will enable full screen loader on the page when ajax call loads the data or ng-repeat is in progress and as things are completed same service will disable the full screen loader
something like this: to make loader service true before calling ajax and make it false as call finishes in success or error.
https://iamlalit.tinytake.com/sf/MTY5MDY2NF81NjM1Njgw
loaderService.toggle(true);
$http({
url: enumApp.url.apiUrl + Id,
method: "GET"
})
.success(function (data) {
loaderService.toggle(false);
})
.error(function (data, status) {
loaderService.toggle(false);
})

Related

Do a reload of mvc/razor partial view with javascript

In my project I have rows of modules loaded from Partial views.
So imagine a grid of small squares with information.
There is a popup dialog for all of them, that displays the data of the clicked module.
Currently when I submit a change in the dialog, the javascript reloads the entire page. BUT, this takes a long time, and I need to be able to refresh only the one dialog.
I can imagine to make a separate js function for each type of module, and then pass some data in, so jquery can find the specific module, and then make an ajax get, for the data. But this requires me to do all the data insertion from js always. instead of using razor and MVC's built in awesomeness.
Does anyone know of a way, to call a partial view inside a div?
Also in the future I will need to reload "some" but not all the modules in an interval refresh. So for future proofing purposes:
What im looking for is something like:
function reloadElement(row, column, id){
var target = $("#div1");
// todo find row and column
target.html.partial("url", model); //<----- looking for something like this. cross fingers.
}
Thanks to GregH for a few key words, that lead to some ideas.
I solved it myself, so if you land on this problem also, here is how i solved it:
Controller:
You want to make your controller return PartialView("somePartialViewUrl", new SomeModel()), apparently saving the model and relying on the data collection isn't good enough, i hadto make a new instance of the model.
Javascript
in the "click" that handles the event, put:
$.ajax({
url: "controllerName/actionName",
data: JSON.stringify({ row:1,column:2 .... }),
contentType: "application/json",
dataType: "html",
type: "POST",
success: function (partial) {
$("#div2").html(partial);
}
});
this will override the html in your "#div2".
im sure you can also use $("#div2").innerHTML = partial; or $("#div2").load("url",parameters); and probably many other ways.
done.

Angular controller not working after window.history.pushstate

$http({
method: 'GET',
url: 'http://localhost:55090/login/login',
}).success(function(data){
// With the data succesfully returned, call our callback
$("html").html("");
debugger
$("html").html(data);
window.history.pushState("object or string", "Title", "/login/login");
}).error(function(){
alert("error");
});
Above code is working, i am able to load the data of another page without refreshing but the the thing is i am using two different angular for both pages.
As soon as i load another html, all the functionality(including models,directives) stopped working.
If you have 2 differents pages the 2nd will probably have his own angular injector created with the ng-app attribute. So you won't have the service/controller of the 1st page.
Angular is meant to be single page application and not to be used with jQuery like this. If you want to perform some navigation check ngRouteor ui-routeron the net.
If you need to add some HTML at a specificed location check $compile and angular.element even though it's not recommanded.

Angularjs - $location.path / $location.url changes URL but doesn't refresh page

Working with Angular and im running into a few issues using $location.url & $location.path
The URL changes at the top of the page to /users/sign_in but I don't see the view until I manually refresh the page, then it appears?
function error(response) {
if (response.status == 401) {
$rootScope.$broadcast('event:unauthorized');
$location.url('/users/sign_in');
};
};
I am not getting any errors.
You're doing a bit too much in your function. You're attempting to change the URL but also return a response. You can try using a $scope.$apply() right after the $location.url call, however you should consider splitting this logic so that the redirect occurs based on the returned response, or don't return any response from the error function.

How to load data prior to page display in AngularJS and Restangular?

I have been using AngularJs with Restangular with PHP backend.
I am calling a function based on route (detail/list) to fetch into variable from Restangular.
The problem is if there is a delay in database connection the page is displayed blank and after a few(2-3) seconds the data is filled and shown,
The issue repeats when navigating to details and going back to the list page.
Here is an example how you can resolve your data before the page is rendered (w/o blank screen):
The 'resolve' function is called before the view is rendered.
$routeProvider.when('/admin/task/:id' , {
templateUrl: '/app/task/admin-task-results.tpl.html',
controller:'AdminTaskDetailsCtrl',
resolve: {
task: function($route, Restangular) {
return Restangular.one('tasks', $route.current.params.id).get();
}
}
});
Just pass the resolved object (task in this example) as argument into your controller:
module.controller('AdminTaskDetailsCtrl', function ($scope, task) { ... });
However, let me point out that this approach is not always the best solution, because the user does not get immediate feedback after changing the route. Consider loading your data in the controller and display a spinner until the data arrived.
I assume that you still need to wait for data loaded, so to draw view without the data and load date later you can use next in the controller constructor:
$scope.$on('$viewContentLoaded', function(){
// Load data into model here
});

jQuery: handling mixed html/js ajax response

Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc states:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string
Which I can confirm by adding a simple snippet to the html reply:
<script type="text/javascript"> alert($(this)); </script>
How then to retain access to the js code vs. one-and-done execution?? Trying to implement a modal login (to prevent data loss on session timeout in form submission screens). Of course I need to be able to access the ajax'd js code to then validate email/password fields and ajax authenticate user credentials on the remote server.
Here's the modal login coffeescript snippet:
# submit form
$.ajax
success: (data) -> ...
error: (data) ->
popAuth(data.responseText) if(data.status == 401)
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
title: title
})
Perhaps I can add a success callback to popAuth() ajax options to store the returned js code? How about jQuery "live" handler? Unfortunate that this scenario is not as straight forward as one would hope ;-) I have seen $.getScript as an option, but would prefer to not separate html from js since server-side already assembles html + js and the original ajax call pulls it all down in one go. (i.e. avoid creating a dedicated server-side controller to send back js file content bundle)
I am of course open to alternative solutions to workaround this issue. For example, I could store login fields and js login validation code on every screen (JVM CRUD application living behind WordPress front end so every screen is basically auth required) in a hidden div, and then pop the modal login window "locally", which I assume would get around the annoying one-and-done js execution of remote ajax content.
Anyway, Ideas appreciated! client-side is both wonderfully simple and...horribly complex ;-)
Ok, fending off the veritable deluge of responses, I'll take a stab myself.
As I understand it now, since mixed html/js content is one-and-done executed, we have one chance to capture ajax response js code and bind it to current scope.
First, in the original ajax call (i.e. form submit that returns a potential 401 not authorized status) set the context of the modal login's ajax setup to $(this), the currently executing scope that contains jquery validation and other shared js code needed for modal login ajax submit to work.
In my case, using fancybox, adding context param it now looks like:
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
context: $(#)
title: title
})
Then, since the parent window contains the majority of needed javascript, the only requirement is to create a js file that binds modal login form button click event to validation and $.ajax submission.
# login.coffee
jQuery ->
$('#loginSubmit').click (e) ->
e.preventDefault()
isValid = $('#loginForm').validate().form()
if isValid
$('#spinner').show()
$.ajax
data: $('#loginForm').serialize()
success: (data) ->
$('#status').fadeOut()
location.href = '/foo'
error: (data) ->
$('#status > div').html( data.responseText )
$('#status').fadeIn()
complete: () ->
$('#spinner').hide()
Done, all good, works ;-)

Categories

Resources