Angularjs Does not work with Jquery load function - javascript

I am creating an web application using ASP.Net MVC5 and AngularJS 1.5, I have a page were data is display from MVC ActionResult and further Edit and Delete operation is perform using AngularJS.
But as I perform edit operation an jsonresult in call from ASP.net MVC controller and perform perfect edit operation with success result, but I also want to refresh the data that is display from MVC ActionResult so I created an partial view and use Jquery load function and pass the URL(MVC ActionResult Url).
The load function refresh the data with current changes in the database but after that AngularJS does not work even AngularJS {{Expressions}} are not working
$http.post('myactionName',{param:param}).success(function (data){
$('#DiV').load("mypartialActionName");
}
<div id="DiV">
#Html.Partial("_PartialViewName")
</div>

first add your jQuery and Angular files, then create the 'app' module
Html
<body configs>
<div id="DiV"> #Html.Partial("_PartialViewName") </div>
</body>
Directive
app.directive("configs", function($http){
return {
link: function(){
$http.post('myactionName',{param:param}).success(function (data){
$('#DiV').load("mypartialActionName");
}
}
}
});

First of all i want to say something if you are using completely AngularJs then do not use #Html.Partial()..use ng-include built in directive instead to inject external template..as of now you are totally depend on MVC that is the bad practice..you have to use MVC for only for server side not Front-end Part and AngularJs uses $http asynchronously you do not have to refresh to to retrieve your data and do not rely on JQUERY..AngularJs can tackle all the things whatever JQUERY did..

Related

express.js how to update UI without refresh all page using handlebars

It's one of the first time that I use express.js and Handlebars.
I need to autocomplete this field: <input type="text" id="myInput" autocomplete="on" placeholder="Search here...">. When everyone digit to this text, I need to make a POST and after a GET without refreshing the content in the page. The problem is, when I do the GET, Handlebars refresh all page. This is the command that I use:
res.render('home',{ items:typeOfCategory});
and this is the structure of the hbs:
{{#if items}}
<ul>
{{#each items}}
<li>{{this.title}}</li>
{{/each}}
</ul>
{{/if}}
My question is: how to avoid the refreshing of the all page?
Thanks
I had read something like that in another question. Based on this tutorial: I found the answer to all my problems.
this tutorial explain how to use a PJAX library that manages both the client and server side.
Thanks to 3 rows of code you can obtain a speed navigation without reload the page.
Install client side library from jQuery-pjax page
into your html page that send the request add: <a href='/yourLink' data-pjax='main'>YourLink</a>
where main is the div that will content yout change. In my case is:
<div id="main" class="main">
{{{body}}}
</div>
In your.js file add $('a[data-pjax]').pjax(); This command 'simply call the pjax extension on every element that contains the data attribute ‘data-pjax’'
Install inside express the depency with the command: npm install --save express-pjax
Set your server:
var app = express();
var pjax = require('express-pjax');
...
app.use(pjax())
Replace the normal rendering:
res.render('index', {title: "Index"});
with
res.renderPjax('index', {title: "Index"});
UPDATE
Alternatively you can obtain the same result. Consider that the structure of the project is as follows:
views
|-> partials
| |-> addtest.hbs
|
|-> index.hbs
For example, image that in your index.hbs you have a sidebar with different items, described in this way:
<li>
<a href="#testDB" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
<img src="../img/database-data.svg" class="svg icon">Test</a>
<ul class="collapse list-unstyled select-specific" id="testDB">
<li value="addTest" class=" ">
Add Test
</li>
....
....
</ul>
</li>
Inside the partials directory you have a simply form.
Now for manage the form you have to do two operations:
Server side: For switching from one partial to another without refresh the page, you specify:
router.get('/addtest', function (req, res) {
res.status(200);
res.header("Content-Type", "text/html");
res.render('partials/addtest', {title: "Add Test"});
});
Client side: In your client side file, you add make a simple get request:
$('#add-new-test').click(function (event) {
$.get('/addtest').then(function (data) {
$('#main').html(data);
});
});
In this way, when you make a get request with the same address (i.e in this case /addtest) the client add a part of code inside your view without refresh all.
NOTE: Keep in mind that, if you needed a some file.js in your partial, for load the file, use this:
<script>
var url = "/scripts/script.js";
$.getScript(url);
</script>
This is used for avoid: “Synchronous XMLHttpRequest on the main thread is deprecated…” because the call is asynchronous. For more info..
The problem here is that you're making the browser request a new resource each time. This is triggering your templating and serving up a brand new page every time.
You'll want to make an express endpoint which returns JSON, and then send up a request to that endpoint using something like AJAX (found in jQuery) or a similar library. This way you can make a call up to your web server, express can return you some data in a JSON format (res.json({}) and your frontend can then interpret that response and decide how to display it on the DOM.
This sort of partial updating is where you start to need frontend JS along side programatic endpoints that return JSON. This is often where some of these big frontend frameworks like Vuejs and Angular thrive, but if you're new to this sort of thing I'd recommend using jQuery to make a HTTP call to your server and return the JSON down to the frontend.

MVC authorization not working when mixed with Angularjs

I have developed an MVC + Angularjs application, a mixed application, and Angular application's first page is my HomeController's Index view as the starting point and now I want to authorize the home page's Index view, but now my MVC authorization attribute is not working and even using with authorization attribute I am able to directly open the Home page.
I need this to be authorized and then that authorized person should open the door to Angular application.
[Authorize]
public ActionResult Index()
{
return View();
}
and this is the Index View, and the starting point of my angularjs application, and other HTML pages are embedded in this view
<div class="row">
<div ng-view>
</div>
</div>
Kindly help me in solving this, and point me what I am doing wrong or I have implemented things wrong. Here is my HomeController's Index action with authorize attribute,
Try this
if you are using ui router you can add this to your app.js
.run(function($rootScope, $location) {
$rootScope.$on("$locationChangeStart", function(event,
next, current) {
if ($rootScope.authenticated == false)
//your code
});
})
For every location change you can check for authentication!

How to execute Laravel controler method by Angular

Let's say I have an laravel controller that contains one method that parsing value from other sites. On client side I'm using Angular. When user presses button it have to execute this Laravel controller method and value that parsed by this method have to fill an input field in form. Im completely new in angular. So is it possible to execute this laravel method from angular? If it is possible can you give some examples how can I achieve this?
this is just a little example to show how to use $http to transport data. I'm not worked with laravel much.
view.html
<html ng-app = 'myAPP'>
<head>
//include required css or js files
</head>
<body>
<div ng-controller = 'MainCtrl'>
<button ng-click = 'sendData()'>Click me</button>
</div>
</body>
</html>
main.js
angular.module('myAPP').controller('MainCtrl',['$scope','$http','$log',function($scope,$http){
$scope.sendData = function(){
$http.post('url',data).success(function(returnData){});
}
}]);
after http post, from laravel controller it must be catch those data in jason format you either can use it in that format or you can decode it and then use it.

Display alert message after page reload

I have to call $route.reload(); in controller 2 addData API call so that I can get the added data in my UI. But then the text 'Data added successfully' goes away due to page refresh.
controller 1:
$rootScope.$on('reloaded', function(event, data) {
$scope.$parent.alerts.length=0;
$scope.$parent.alerts.push({type: 'success',msg: 'Data added successfully'});
});
controller 2:
$scope.add = function() {
someAPIService.addData(JSON.stringify($scope.rows)).success(function(response) {
ngDialog.close('ngdialog1');
$route.reload();
$rootScope.$emit('reloaded', "true");
});
}
HTML Part:
<section>
<div ng-controller="controller3">
<alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>
</div>
<div class="row form-inline" ng-controller="controller2 as vm">
<!-- Table data with text fields-->
</div>
<script type="text/ng-template" id="addDataDialog">
<div id="frm" ng-controller="controller1" class="col-xm-6">
<div class="form-group">
<!-- Labels with text fields-->
</div>
<button class="ngdialog-button" ng-click="add()">Save</button>
</div>
</script>
</section>
NOTE: Both controllers are in the same JS file and they are used for the same HTML file.
As you want to only load the latest record list which is on server side. Then there is not need to use $route.reload(); after making post call. You need to only make ajax call to get the latest records list that will solve your problem. For making ajax you need to refer $http
$route.reload() is getting used only when you need to load
controller again with specified template in your $routeProvider when
condition
just a simple hint of an answer:
add a (specific) cookie (with javascript) before calling reload (use e.g Cookies lib),
read it on reload,
and then delete it
Also you may use local storage if it is available instead of a cookie using same steps:
add a specific entry in local storage, before calling reload
read it on reload
and then delete it
Another option to maintain state client-side is to use url parameters but these will not do for page reload

ASP.NET MVC 2.0 Ajax call - LoadingElementId not re-hidden when OnSuccess script specified

I'm writing a very simple web application in ASP.NET MVC 2.0 which is used as a test interface for a web service. The various pages present a user interface to input the parameters for the request messages. The parameters are submitted back to the controller via Ajax, which returns a partial view containing the response SOAP message (HTML encoded XML) in a <pre> tag...
// In controller...
ActionResult WebMethodTest()
{
return View(new WebMethodModel());
}
[HttpPost]
ActionResult WebMethodTest(WebMethodModel model)
{
model.Response = MyServiceProxy.WebMethod(model.Request);
return PartialView("SoapResponse", model.Response);
}
// In view
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId="Response", LoadingElementId="Loading", HttpMethod="POST", OnSuccess="prettyPrint"}))
{ %>
<!-- various model bound controls... -->
<% { %>
<div id="Loading" style="text-align:center; display:none">
<img src="../../Content/ajax-loader.gif" alt="loading..." /><br />
working...
</div>
Unfortunately the Loading div element is not being hidden again when the data is returned after the Ajax call, it stays visible. Interestingly, it does get hidden correctly if I remove OnSuccess="prettyPrint". I get the impression that my OnSuccess script is overriding the default behaviour, rather than executing in addition. I don't want to lose prettyPrint though as it's colourizing the XML which is being displayed... how can I keep the default loading element behaviour as well as my own OnSuccess hook?
Cheers!
I resolved this issue by amending the OnSuccess script to this:
OnSuccess = "function() { prettyPrint(); return true; }"
So it seems that, like OnBegin, returning false (or anything other than true) cancels the operation, although by this stage the DOM has already been updated, so the only thing you can canel is hiding the Loading element... which doesn't seem terribly useful!

Categories