How load dynamic and well separeted part of views with callback - javascript

I have an architectural problem that I can't find an angular-oriented solution. My application has several objects that interact through modals.
For Example:
I can create a new color from functionality of colors management. My creation works through a modal, and in this case the modal will refresh the list of colors behind it.
But when I create a new product I also can create color through this SAME modal. In this case, the modal will refresh my product screen.
With the url and using ajax I can append this modals in html and work with any modal that my system provides in anywhere.
I want to give a different callback for each kind of caller, if possible through the digest cycle of the angular caller scope. But I want to keep my modal independent of the caller.
Note: I don't know the modals that my functionality will need on load, i just know it when the user interacts with the links.
Could I do something like this with angular ?
Here some example:
$(function() {
$('.js-content-link').click(function() {
//here normally is a ajax request with parameters
var url = $(this).data('file');
$.get(url, function(data) {
$('#main-content').html(data);
$('.js-modal-link').click(onClickModalLink);
});
});
var loadModal = function(html) {
$('#modal-content').html(html);
$('.js-modal-link').click(onClickModalLink);
};
var onClickModalLink = function() {
//here normally is a ajax request with parameters
$.get($(this).data('file'), loadModal);
};
})
Plnkr link:
https://plnkr.co/edit/rJdfGC?p=preview

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.

JS recreate eventlistener

I'm working with JQuery and ajax.
SCENARIO:
The scenario is the following.
I have a table with different features and each row has it's own button to call "show data " function. With the first call I check some microservices that manipulated the origin data. If data is available ,I show a button for every manipulated data to show in a chart. Every Button gets a listener created in de success method of an ajax call. So there can be three scenarios:
First: show data is called the first time. So there is no
Eventlistener created yet. In that case I create I new one for each
button.
Second: Imagine I clicked a button to show the data in a chart. After
that, the chart gets closed. Now I want to show the same data again.
So my Eventlistener should stay the same and there should not be
another one added.
Third: I click another feature in the table which might have data the
is manipulated differently or will be shown in another chart (e.g. pie
chart insted of flow chart.) So the scenario is pretty much like in
case one but now there is an old Listener to delete.
As a summary: I have to save the Eventlistener Object persistend when it gets createt because when case 3 turns up, I want to call removeEventlistener but I get an error that this object is not defined:
I'm a total noob in js.
This scenario results in the problem, that the eventarguments are not updated and you can see that the data output of listeners pops up for a second and gets overlayed by newer.
And when you do a few attemps, it ends in chaos where nothing fits. By this I mean the wrong data is shown in a wrong chart (one of an older event.).
So I wanted to delete the old listener and recreate it.
Is this a possible solution or is there a better way to do it?
The whole funtion looks like this:
function showData(id,category,feature,date,caller,already_called){
document.getElementById("originButtonDiv").style.visibility='visible';
document.getElementById("squareButtonDiv").style.visibility='hidden';
try{
//show data again -> maintain listener
if(old_already_called == 0 && already_called == 1){
old_already_called = already_called;
}
//New feature choosen -> Delete old listener and create new one
if(old_already_called == 1 && already_called == 0){
$.ajax({
type:'GET',
url:"${path}/user/...
dataType:'text',
async: false,
success:function genTable(data){
var originDataButton = document.getElementById("originDataButton");
//originDataButton.removeEventListener("click",_listener,true);
originDataButton.addEventListener("click", function _listener(){
originDataButtonClicked(id,category,feature,date);
}, true);
if(data.localeCompare("true")==1){
document.getElementById("squareButtonDiv").style.visibility='visible';
var squaredDataButton = document.getElementById("squaredDataButton");
//squaredDataButton.removeEventListener("new_click",_squared_listener,true);
squaredDataButton.addEventListener("click",function _squared_listener(){
squaredDataButtonClicked(id,category,feature,date);
}, true);
}
}
});
old_already_called = 0;
}
}
catch{
//first call --> create new Eventlistener
$.ajax({
type:'GET',
url:"${path}/user/...
dataType:'text',
async: false,
success:function genTable(data){
var originDataButton = document.getElementById("originDataButton");
originlistener = originDataButton.addEventListener("click", function _listener(){
originDataButtonClicked(id,category,feature,date);
}, true);
if(data.localeCompare("true")==1){
document.getElementById("squareButtonDiv").style.visibility='visible';
var squaredDataButton = document.getElementById("squaredDataButton");
squaredDataButton.addEventListener("click",function _squared_listener(){
squaredDataButtonClicked(id,category,feature,date);
}, true);
}
}
});
old_already_called = 1;
}
}
Update:
I'm pretty sure now that the problem is the usage of ajax. I defined a logic tree for my use case because I have to detect whether an Eventlistener should be created, persist unchanged or deleted and recreated. I guess I can differentiate these circumstances in my code but the problem is, that I define the listener in the ajax success method. Between two calls the listener is undefined. So is there a possibility to save a listener object peristent on the client between to ajax calls so that I can delete it within future calls? I guess this would be the solution for my problem.

Browser network trace showing JSON post creating same file/link for every posting JQuery

I am using Json post method to get data from controller and display the data on Razor view page using dropdown list. When I am tracing browser network tab, I can see it is creating and keeping every post request and increasing the file size. I am new for JQuery. My question is, there are any way I can remove the previous post. Please see the image file below where I posted twice from dropdown list. I always want to keep the last post.
Please click to see the image
My JQuery code is -
$(document).ready(function ()
{
$('#ddl2').change(function (e)
{
e.preventDefault();
var data1 = {str_test: str_test };
var url = '#Url.Action("ddl_2")?id=' + id;
$.post(url, data1, function (data)
{
$('#nav_div').html(data);
});
});
});
Thanks
Either you're posting multiple time or you've called the same function with same selector each time. You could post your JS logic code here to debug correctly otherwise assumption answer aren't helpful.

$window.location.href doesn't reload whole page in AngularJs

I'm using a code like this to create an account and than i want to validate (with some specifics functions) and after that redirect to the main page.
$scope.createAccount = function(cad) {
$http.post('dist/func.php?action=createAccount', cad).then(
function(res) {
//..more functions
$window.location.href = '/adm';
},
function(err) {
Notification.error(feedbackError);
}
);
};
The problem is, when the user arrive in the new page, the mainCtrl is not running (the page is not fully reloading) so i can't get essential data for this new user.
I saw some other similar questions, but all of them says we should use $window.location.href instead of $location to get a full page reload. But until now, i had no success with it.
How can i solve it?

How do I prevent a method from firing before I receive data from my server?

So I am using backbonejs to generate a html page base on a data that I receive from google datastore. The problem I'm have is trying to stop my render method from returning before I the data is received.
A little side question: Is it possible to open a window.open() passing in html?
Instead of calling window.open() with html in it (basically you are passing some data), you can open your window by window.open() and after that call your predefined funciton in that window and pass your data (or your HTML) to that function and let it do your job :)
Why fight it? Load up your page with spinners in the areas where the google data will go. When the google data finally comes back, update backbone with that data and render again; this time with the data instead of the spinners.
If you really want to fight it, you can cause jQuery ajax calls to run synchronously with the async option. Add async: false to the options you are passing in to the ajax call.
jQuery.ajax() Documentation
In your Collection:
var c = Backbone.Collection.extend({
url: '/path/to/api',
initialize: function() {
this.deferred = this.fetch();
}
});
In your View:
var v = Backbone.View.extend({
render: function() {
c.deferred.done(function() {
/* Render your View here */
});
}
});
This is made possible due to collection.fetch() returning a jqXHR. More explanations here.

Categories

Resources