Display Loading Icon while loading data for specific time using angularjs - angularjs

I am trying to load Image icon(set time to load particular for 30 Second) while loading the data from the database but I am facing some problem as I want to set timer also for Loading Icon (i.e Loading Icon appear for 30 second) using angularjs. How I achieve this functionality as I was done this by ng-show and ng-hide but I am unable to attach time in Icon.
my Code is
editApp.controller('MyCtrl', ['$scope', '$http', 'ngDialog','$timeout' ,function ($scope,$http, ngDialog, $timeout) {
GetList();
$scope.dataloaded = false;
and after ajax call I set $scope.dataloaded to true
function GetList() {
debugger;
$http({
method: 'GET',
url: '/Home/GetProductList'
}).
success(function (data) {
if (data != null || data != 'undefined') {
$scope.productlist = data;
$scope.dataloaded = true;
}
})
.error(function (error) {
$scope.status = 'Unable to retrieve product' + error.message;
});
}
and my html code is
<div ng-hide="dataloaded" style="margin:auto" align="center"> </div>
and
<div ng-show="dataloaded" style="margin:auto" align="center"> </div>

Lets show div for 30 sec:
<button ng-click='show()'>Show</button>
<div ng-show='showDiv'/>
In controller:
$scope.show = function() {
$scope.showDiv = true;
$timeout(function() {
$scope.showDiv = false;
}, 30000);
}

Related

MEAN with Jade template form submit GET instead of POST

So, earlier today I had a working form that could post and delete restaurants documents to a mongodb collection. Everything was working fine, but then I decided to try and load the form into a div instead of redirect to a new page. Doing so produced a different result when I tried to submit my restaurant form. Originally it would call $scope.add() in my restaurantsController, but now it is sending a GET request with form data to /restaurants instead of a POST to /api/restaurants. I'm looking for some insight as to what I did to change the behavior. Although it is loading the form when I click on my restaurant anchor tag, it is not loading the restaurants from the database.
Here is the jade and js for the menu anchors:
menu.js
app.controller("menu", ["$scope", "$http", function ($scope, $http) {
$scope.home = function () {
$("#content").html("");
};
$scope.restaurants = function () {
$http.get('/restaurants').
success(function(data, status, headers, config){
$("#main_content").html(data);
}).
error(function(data, status, headers, config){
});
};
}]);
nav.jade
mixin link(name, fn)
li
a.btn(ng-click=fn)= name
nav.navbar.navbar-inverse.navbar-fixed-top(role='navigation')
.container
.navbar-header
button.navbar-toggle.collapsed(type='button', data- toggle='collapse', data-target='#navbar', aria-expanded='false', aria- controls='navbar')
span.sr-only Toggle navigation
span.icon-bar
span.icon-bar
span.icon-bar
a.navbar-brand(href='/') Food App
#navbar.navbar-collapse.collapse
ul.nav.navbar-nav(ng-controller="menu")
+link("Home", "home()")
+link("Restaurants", "restaurants()")
And here is the form:
form(name="NewRestaurant" ng-submit="$event.preventDefault();add()")
.row
.form-group
input.form-control(type="text", name="name" placeholder="Name", ng-model="name" required)
.row
.form-group
input.form-control(type="text", name="address" placeholder="Address", ng-model="address" required)
.row
.form-group.col-md-6
-for(var i = 0; i <= 5; i++){
input(name="rating" type="radio", value=i, ng-model="rating" required)
=i
-}
.form-group.col-md-6
button.success(type="submit") Submit
and the controller...
app.controller("restaurants", ["$scope", "$resource", function ($scope, $resource) {
var Restaurant = $resource('/api/restaurants/:id');
var clearForm = function () {
$scope.name = '';
$scope.address = '';
$scope.rating = null;
}
clearForm();
var validRestaurant = function () {
if($scope.name !== '' && $scope.address !== '' && $scope.rating !== null)
return true;
else{
toastr.error("Please fill in all required form fields.");
return false;
}
}
$scope.query = function(){
Restaurant.query(function (results) {
$scope.restaurants = results;
});
};
$scope.add = function () {
alert("got here!");
if(validRestaurant()){
var restaurant = new Restaurant();
restaurant.name = $scope.name;
restaurant.address = $scope.address;
restaurant.rating = $scope.rating;
alert(restaurant);
Restaurant.save(restaurant, function (result) {
$scope.restaurants.push(result);
toastr.success("Saved " + $scope.name + ".")
clearForm();
});
}
};
$scope.update = function (id) {
};
$scope.remove = function (id) {
console.log(id);
Restaurant.delete({id: id}, function (err) {
console.log(err);
$scope.query();
});
};
$scope.query();
}]);
edit: Now that I am typing this up, I am wondering, maybe angular doesn't recognize the form and doesn't create a $scope for it because it gets loaded after the page loads...?

Is there a better way to disable a button when posting data in AngularJS?

In my projects at the moment, I use something along these lines for AJAX forms.
$scope.posting = false;
$scope.submitForm = function(form){
log(form);
log((!form.$invalid) ? 'Is valid' : 'Contains errors');
$scope.posting = true;
$http.post('/modules/ajax/addModule', $scope.module)
.success(function(data, status, headers, config){
data = data.data;
log(data);
$scope.posting = false;
if(data.error){
alert(data.message);
}
})
.error(function(data, status, headers, config){
data = data.data;
log(data);
$scope.posting = false;
});
}
and on the submit button, <input ng-disabled="form.$invalid || posting" ... />
Whilst it's not much to type code, manually switching the bool value seems a little non Angular to me. Is there anyway to tell if an $http.post is still active?
just write a directive which will disable and enable the button on http calls, like below
app.directive('onClick', function() {
return {
scope: {
onClick: '&'
},
link: function(scope, iElement, iAttrs) {
iElement.bind('click', function() {
iElement.prop('disabled',true);
scope.onClick().finally(function() {
iElement.prop('disabled',false);
})
});
}
};
});
note : onClick function should return a promise for this to work
Checkout this plunker to see it in action
I use angular-ladda for button with spinner while call is in progress
What I ended up doing was adding this code to my global JS file.
app.run(function($rootScope, $http) {
$http.defaults.transformRequest.push(function (data) {
$rootScope.$isPosting = true;
return data;
});
$http.defaults.transformResponse.push(function(data){
$rootScope.$isPosting = false;
return data;
})
});
Then I can just use
<a ng-disabled="isPosting" ...

How to Dismiss Angular Modal

I am using Ekathuwa modals, I need to close it after a successfull Ajax PUT. I am trying to follow the examples they give. I am able to close the modal, but there is still a grey color on the screen. Like it is still open in the background? I still need to refresh the page for it to go away.
$scope.updateJob = function (job) {
console.log($scope.currentItem);
job.JobTypeId = $scope.currentItem.JobType.JobTypeId;
job.JobClassId = $scope.currentItem.JobClass.JobClassId;
job.GeoAreaId = $scope.currentItem.GeoArea.GeoAreaId;
jobFactory.updateJob(job).success(successCallback)
.error(errorCallback);
console.log(job);
var p = $ekathuwa.modal({
id: "EditJobModal", contentStyle: "width:800px;heigth:400px",
scope: $scope,
templateURL: "views/modals/EditJobModal.html"
});
$q.when(p).then(function (m) {
m.modal('hide');
});
};
var successCallback = function (data, status, headers, config) {
notificationFactory.success();
};
var errorCallback = function (job, status, headers, config) {
notificationFactory.error(job.ExceptionMessage);
};
Move hide modal logic to successCallback function.
I don't know your editable fields on "views/modals/EditJobModal.html" or other pages.
If it is on EditJobModal.html, Better to used two functions, one for create and open modal other for your update logic.
thanks,
Sarath
Update
//Edit Job Modal
$scope.EditJobModal = function (id) {
$.get('/api/apiJob/' + id, function (data) {
console.log(data);
$scope.currentItem = data;
$scope.openEditJobModal = $ekathuwa.modal({
id: "EditJobModal", contentStyle: "width:800px;heigth:400px",
scope: $scope,
templateURL: "views/modals/EditJobModal.html"
});
//show modal window
$scope.openEditJobModal.then(function (m) {
m.modal('show');
});
});
}
//Update Job
$scope.updateJob = function (job) {
console.log($scope.currentItem);
job.JobTypeId = $scope.currentItem.JobType.JobTypeId;
job.JobClassId = $scope.currentItem.JobClass.JobClassId;
job.GeoAreaId = $scope.currentItem.GeoArea.GeoAreaId;
jobFactory.updateJob(job).success(successCallback)
.error(errorCallback);
console.log(job);
};
var successCallback = function (data, status, headers, config) {
//hide modal window
$scope.openEditJobModal.then(function (m) {
m.modal('hide');
});
notificationFactory.success();
};
var errorCallback = function (job, status, headers, config) {
notificationFactory.error(job.ExceptionMessage);
};
Modal
<input type="submit" ng-click="updateJob(currentItem)" value="Submit" />
<input type="button" ng-if="true" data-dismiss="modal" value="Exit" />
Seems to be a bug in AngularUI. See this: https://github.com/angular-ui/bootstrap/issues/1643
The modal scope is not being destroyed correctly on either close or dismiss.

Angular Two way databinding and http.post issue

Objective: Two Way Databinding between database and view via scope and controller
I’m trying to post to a restful database using angular
When I click on the thumbs up or thumbs down the scope changes o.k and is reflected in the view
However how can this placed in real time to a restful database using http post ?
Here’s the HTML
<div ng-controller="ordersCtrl">
<div class="span0 well votingWidget">
<div class="votingButton" ng-click="upVoteOrder(order)">
<i class="icon-thumbs-up "></i>
</div>
<div class="badge ">
<div>{{order.upVoteCount}}</div>
</div>
<div class="votingButton" ng-click="downVoteOrder(order)">
<i class="icon-thumbs-down"></i>
</div>
Heres the Controller: My issue lies here in the http.post command
.controller("ordersCtrl", function ($scope, $http, ordersUrl) {
$scope.downVoteOrder = function(order) {
$scope.selectedOrder = order;
order.upVoteCount--;
$http.post(orderUrl, order.upVoteCount)
.success(function (data) {
$scope.data.orderupVoteCount = data.id;
})
};
});
Note : I can post form data to the restful database successfully using the following code
$scope.sendOrder = function (shippingDetails) {
var order = angular.copy(shippingDetails);
order.products = cart.getProducts();
$http.post(orderUrl, order)
.success(function (data) {
$scope.data.orderId = data.id;
cart.getProducts().length = 0;
})
.error(function (error) {
$scope.data.orderError = error;
}).finally(function () {
$location.path("/uploaded");
});
}
you should use a separate service to handle the http post .
var app = angular.module("myApp", []);
app.factory("OrderService", ["$http", function ($http) {
this.PostDownVote = function(orderUrl, upVoteCount) {
return $http.post(orderUrl, upVoteCount);
}
this.PostOrder = function(orderUrl, order) {
// do something
}
return this;
}]);
Now inject this OrderService to you controller and use it.
app.controller("ordersCtrl", function ($scope, $http, ordersUrl, OrderService) {
$scope.downVoteOrder = function(order) {
$scope.selectedOrder = order;
order.upVoteCount--;
OrderService.PostDownVote(ordersUrl, order.upVoteCount)
.success(data) {// do something}
.error(data) {// do something}
}
});

AngularJS: model data from http call not available in directive

There seems to be a bug where model data fetched from an http call is present in the $scope but not in a directive. Here is the code that illustrates the problem:
Jsfiddle: http://jsfiddle.net/supercobra/hrgpc/
var myApp = angular.module('myApp', []).directive('prettyTag', function($interpolate) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
var text = element.text();
//var text = attrs.ngModel;
var e = $interpolate(text)(scope);
var htmlText = "<b>" + e + "</b>";
element.html(htmlText);
}
};
});
function MyCtrl($scope, $http, $templateCache) {
$scope.method = 'JSONP';
$scope.url = 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero';
$scope.fetch = function () {
$scope.code = null;
$scope.response = null;
$http({
method: $scope.method,
url: $scope.url,
cache: $templateCache
}).
success(function (data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
The HTML
<div ng-controller="MyCtrl">
<h1>Angular $http call / directive bug</h1>
<p>This fiddle illustrates a bug that shows that model w/ data fetched via an http call
is not present within a directive.</p>
<hr>
<h2>HTTP call settings</h2>
<li>Method: {{method}}
<li>URL: {{url}}
<br>
<button ng-click="fetch()">fetch</button>
<hr/>
<h3>HTTP call result</h3>
<li>HTTP response status: {{status}}</li>
<li>HTTP response data: {{data}}</li>
<hr/>
<h2>Pretty tag</h2>
<pretty-tag>make this pretty</pretty-tag>
<hr/>
<h3 style="color: red" >Should show http response data within pretty tag</h3>
[<pretty-tag>{{data}}</pretty-tag>] // <=== this is empty
</div>
Jsfiddle: http://jsfiddle.net/supercobra/hrgpc/
Any help appreciated.
You are replacing the content of the directive in your directive implementation. Since the $http request is async, the directive completes before the data is retrieve and assigned to the scope.
Put a watch on data variable inside the directive and then re-render the content, something like
scope.$watch(attrs.source,function(value) {
var e = $interpolate(text)(scope);
var htmlText = "<b>" + e + "</b>";
element.html(htmlText);
});
Based on #Marks feedback and your request i have update fiddle
http://jsfiddle.net/cmyworld/V6sDs/1/

Resources