How to wait for response in angularjs - angularjs

What I am doing is putting the filter on table (contains records). When I type into search box (used http get method), table data get updated as per search box. But when I type very fast, then I see in console 500 Internal Server error.
The main problem is before comming previous response I am firing the next request.
There is no problem in result. Just console shows every http request. And in case of fast typing in search box it gets red.
What is the solution for it?

you could trottle your search input :
var app = angular.module('app', []);
app.controller('TableController', function($scope, $http, $timeout) {
$http.get('yourTableData.json').then(function(result){
$scope.rows = result.data;
});
$scope.filterText = '';
var temp = '',
filterTextTimeout;
$scope.$watch('searchText', function (val) {
if (filterTextTimeout){
$timeout.cancel(filterTextTimeout);
}
temp = val;
filterTextTimeout = $timeout(function() {
$scope.filterText = temp;
$http.get($scope.filterText).then(function(result){
$scope.rows = result;
}
}, 250);
})
});
<input id="searchInput" type="search" placeholder="search field" ng-model="searchText" />
<div class="record" ng-repeat="row in rows | filter:filterText">
<span>{{row.content}}</span>
</div>

Related

Angularjs scope data inside the function

I am trying to display the data to my view but $scope.plan outputs {}. I am thinking that it would output the fetched data from the initGetEdit function, console.log() inside the $http.post outputs expected data.
controller.js
var id = $stateParams.id;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
$http.post("someUrl", data).then(function(res){
$scope.plan = res.data;
console.log($scope.plan); //----> logs expected data
})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
In my view I have something like this.
view
<input ng-model="plan.something" type="text" />
UPDATE
First thank you for those answers provided and the comments, appreciated it. It gives me an insight. I solved my issue by removing the initGetEdit function and staying with just the http.post.
Try keeping the second console in watch.
$scope.$watch('plan',function(){
console.log($scope.plan);
});
At first, you declare a variable $scope.plan = {} after that in http call of your $scope.initGetEdit function its empty object after the function http is an async call your object may be filled based on the response. until that it will be an empty object.
#Ujjwala Bollam mention in answer to print it in the console.
var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope,$http){
//var id = $stateParams.id;
var id=1;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
//$http.post("http://someurl", data).then(function(res){
$scope.plan ={id:1,something:"hai this is response data"};
console.log($scope.plan); //----> logs expected data
//})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<input ng-model="plan.something" type="text" />
</div>

Validation still saves null fields in DB

I'm a newbie to AngularJS. I need to validate the fields so when the user types empty information, the error is shown and data still does not save into DB. If information is valid then ofcourse it must be saved into my DB
The messages works fine, however content still gets saved if the user leaves empty fields and hits submit.
Below is my validation of the controller:
app.controller('addContactCtrl', ['$scope', '$http', function($scope, $http)
{
$scope.newContact = function(contact) {
$scope.queryMsg= ""; //displays if sent or not in html form
//post is used to create
$http.post('model/addContact.php', contact).success(function(data) {
if (data && contact != "")
{//row inserted into table
$scope.queryMsg = "Query has been sent successfully.";
$scope.contact = "";
}
else
{
$scope.queryMsg = "Fields cannot be left empty.";
}
})
};
}
]);
Thanks for your help!
I would validate on the form.
The submit button will be disabled until the form is valid, you can use ng-messages to show a message.
you can read more about it https://scotch.io/tutorials/angularjs-form-validation
<form name="myForm">
<input ng-model="data" required>
<input ng-model="contact" required>
<button ng-disabled myform.$invalid >submit</button>
</form>
You might need to validate it before posting the data. You doing validation after post. Please try this
app.controller('addContactCtrl', ['$scope', '$http', function($scope, $http)
{
$scope.newContact = function(contact) {
$scope.queryMsg= ""; //displays if sent or not in html form
//post is used to create
if (contact != "") {
$http.post('model/addContact.php', contact).success(function(data) {
if (data){
$scope.queryMsg = "Query has been sent successfully.";
}
})
} else {
$scope.queryMsg = "Fields cannot be left empty.";
}
};
}
]);

Insert data into existing child firebase

First of all, I want to apologize for my poor English.
The last week I started to explore AngularJS in the Ionic framework with Firebase as backend. But I’ve stumbled upon a problem that I can’t solve for the past 3 days.
The purpose is when I chose a storage place and confirm it, an inventory will be created with a date and a link to the storage place to know to which storage place the inventory belongs. After that a list of products will be shown. When you chose a product, a new screen appears where you can add the amount of that product.
My problem is, I can create an inventory after confirmation, but it seems like I can’t insert the product with the amount inside the just created inventory.
Before insertion:
- Inventories
- Date: 1449767729166
- storage: "My Storage place 1"
I want my database looks like this after the insert:
- Inventories
- Date: 1449767729166
- storage: "My Storage place 1"
- Products:
- Name: Heineken
- Boxes: 12
- Bottles: 6
Here is my code:
addProducts.html
<div class="list">
<label class="item item-input item-floating-label">
<span class="input-label"><p>Aantal volle bakken/boxes</p></span>
<input type="text" placeholder="Aantal volle bakken/boxes" ng-model="products.boxes">
</label>
<br>
<label class="item item-input item-floating-label">
<span class="input-label"><p>Aantal (losse) flessen</p></span>
<input type="text" placeholder="Aantal (losse) flessen" ng-model="products.flessen">
</label>
<br>
<button class="button button-block button-dark" align="left" ng-click="AddProducts(products)">
Toevoegen
</button>
</div>
controllers.js:
.controller('AddProductCtrl', function($scope, $state, Inventory, Product) {
$scope.products = Inventory;
$scope.products = Product;
var now = Firebase.ServerValue.TIMESTAMP;
$scope.AddProducts = function(products) {
var query = Product.orderByChild(products.storage).equalTo('now');
query.once('child_added', function(snapshot) {
snapshot.ref().child('Products').push({
'Boxes' : fullBox,
'Bottles': losFles
});
});
}})
services.js
.factory('Product', ['$firebaseArray', function($firebaseArray) {
var addProductRef = new Firebase('https://testdb-1.firebaseio.co/Inventories/');
return $firebaseArray(addProductRef); }])
My Firebase structure:
Firebase structure
This is the error I got:
Error: Product.orderByChild is not a function
I already tried serveral things but with no success.
I'm really new to this. So, please point out what I did wrong.
Thanks in advance!
Your Product factory returns a $firebaseArray, which does not have an orderByChild() method.
I can't really figure out your use-case, but one way to solve the error message:
.factory('Product', ['$firebaseArray', function($firebaseArray) {
var addProductRef = new Firebase('https://testdb-1.firebaseio.co/Inventories/');
return addProductRef;
}])
So instead of returning a $firebaseArray this returns a Firebase reference, which has the orderByChild method you're looking to use.
And then:
$scope.AddProducts = function(products) {
var query = Product.orderByChild(products.storage).equalTo('now');
query.once('child_added', function(snapshot) {
snapshot.ref().child('Products').push({
'Boxes' : fullBox,
'Bottles': losFles
});
});
I believe the confusion comes from mixing up the Firebase SDK with the AngularFire API.
You properly create Products factory using a $firebaseArray(), but then you try to use it like a regular Firebase reference.
A $firebaseArray() takes in a Firebase references and wraps all of the child events (child_added, child_changed, etc...) and create a synchronized array.
You can try using a factory to get the products:
.constant('FirebaseUrl', '<my-firebase-app>')
.service('rootRef', ['FirebaseUrl', Firebase])
.factory('productsByDate', function(rootRef, $q) {
return function productsByDate(storage) {
var deferred = $q.defer();
var productRef = rootRef.child('products'); // or however you get there
var localNow = new Date().getTime();
var query = Product.orderByChild(storage).equalTo(localNow);
query.once('value', function(snapshot) {
deferred.resolve(snapshot);
});
return deferred.promise;
};
});
Try this in your controller:
.controller('AddProductCtrl', function($scope, $state, Inventory, Product, productsByDate) {
$scope.products = Inventory;
$scope.products = Product;
var now = Firebase.ServerValue.TIMESTAMP;
$scope.AddProducts = function(products) {
// get your products by date
productsByDate(products.storage).then(function(snapshot) {
snapshot.ref().child('Products').push({
'Boxes' : fullBox,
'Bottles': losFles
});
});
});
});

WebSQL query causing $digest reached 10 iterations error

I'm using Angular and WebSQL in a Cordova project, and I've started a new list controller that will list the results of a table from the WebSQL database.
I have a sqlSvc that queries the database like so:
service.upc = function(newUpc) {
var deferred = $q.defer();
var resolveResults = function (tx, results) {
deferred.resolve(results.rows);
}
var selectUpcs = function() {
var queryString = "SELECT * FROM UPC";
service.db.transaction(function (tx) {
tx.executeSql(queryString, [], resolveResults, rejectWithError);
});
}
deferUntilInit(function () {
if (newUpc) {
insertOrReplaceAndSelect(newUpc); //omitted
} else {
selectUpcs();
}
});
return deferred.promise;
}
All the controller does is this:
var listCtrl = function($scope, sqlSvc) {
sqlSvc.upc().then(function(result) {
$scope.list = result;
});
}
angular.module("RDb").controller("listCtrl", ["$scope", "sqlSvc", listCtrl]);
And it's binding to a simple UI view template:
<div id="scanList">
<ul class="list-unstyled">
<li ng-repeat="scan in list">
<div>{{scan.upc}} ({{scan.datetime}})</div>
</li>
</ul>
</div>
This is giving me the 10 $digest iterations reached error, and it seems to be caused by the way WebSQL is return its results. The error goes away if I deep copy the data, changing resolveResults to:
var data = JSON.parse(JSON.stringify(results.rows));
deferred.resolve(results.rows);
I would like to be able to get this service to work without having to deep copy every results set that it gets. Can anyone help me understand why this is happening?

I am not able to pass my recent values added in service method to html page

This is my first html page where I need to populate my recently added data:
<div>
<!--I have binded busdomain through controller -->
<swt-tree tree-data="busdomain"</swt-tree>
</div>
This is my child html page which is called under first page and I want to pass the values entered on this page to my parent page. But not getting recent values until I reload the page.
<span ng-show="true"</span>Name</label>
<div class="col-sm-9">
<input focus="" id="name" placeholder="Name" ng-model="busdomain.name" ng-change="domainNameChanged()" required="true">
</div>
<button type="submit" ng-click="addSubTree(createdomain.$valid)" id="btnData">OK</button>
This is my controller, I have called service through controller:
controller('domainController', ['$scope', '$state', 'DomainNameService', function($scope, $state, DomainNameService) {
$scope.activeTab = 1;
$scope.currentBDStatement=[];
$scope.statements=[];
$scope.childBD =[];
$scope.busdomain=[];
<!--It is used when I navigate from parent to child for the first time -->
$scope.busdomain = DomainNameService.getBusDomainName();
$scope.addSubTree = function(val){
//Done some code here
//In $scope.statements I am getting the values which I need to pass on html page
//I am setting the value in service which I got from my child html page
DomainNameService.setBusDomain($scope.statements);
//Here I am calling the get method of my service and able to get the values which i have set.
$scope.busdomain = DomainNameService.getBusDomainName();
//Redirecting to my parent page here I want to show the values which i have set in $scope.busdomain but I am not getting recent added values..
$state.go('BusDomainTree');
}
This is my service.js:
Here I have used getter and setter:
app.factory('DomainNameService', function() {
var busDomain = undefined;
var busDomainValue=[];
setBusDomain:function(busDomName){
this.busDomainValue=busDomName;
},
getBusDomainName: function(){
<!--I am getting the values here which I need to pass to html page -->
return this.busDomainValue;
}
})
Full controller code:
controller('domainController', ['$scope', '$state', 'DomainNameService', function($scope, $state, DomainNameService) {
$scope.activeTab = 1;
$scope.currentDomain = {};
$scope.currentBDStatement=[];
$scope.statements=[];
$scope.childBD =[];
var statementTree = {};
$scope.busdomain=[];
$scope.domain = DomainNameService.getDomainName();//Getting parent name here
$scope.busdomain = DomainNameService.getBusDomainName();
//$scope.busDom = DomainNameService.getBusDomainModel($scope.statements);
$scope.addTree = function(isValid) {
if(isValid) {
var stType = $scope.domain.name;//Getting value from html page of parent
$scope.currentDomain = $scope.getNewDomain(stType,varType);
$scope.statements.push($scope.currentDomain);
//Adding parent name to tree code $scope.statementTree.setNewInput($scope.statements);
$scope.isAdd = false;
DomainNameService.addDomain($scope.domain.name);
$scope.domain.domainName = DomainNameService.getDomainName()[0];
$state.go('DomainTree');
}
}
$scope.getNewDomain = function(stType,varType) {
//passing parent name as json
return {domainNode:[{name:stType}],name:stType, varName:varType};
}
$scope.addbusinessDomain = function() {
$state.go('DomainTree.businessDomain');
}
//This method is called for child
$scope.addSubTree = function(val){
var varType = "busDomain";
var domain=[];
var busDomainName=$scope.busdomain.name;
var parent = DomainNameService.getDomainName()[0];
DomainNameService.addChildBD(busDomainName);
$scope.childBD=DomainNameService.getChildBD();
$scope.currentStatement = $scope.busdomain.name;
$scope.currentBDStatement.push($scope.busdomain.name); $scope.currentDomainName=$scope.getBusDomain($scope.childBD,parent,varType);
$scope.statements.push($scope.currentDomainName);
$scope.statementTree.setNewInput($scope.statements);
DomainNameService.setBusDomain($scope.statements);
$scope.busdomain = DomainNameService.getBusDomainName();
$state.go('BusDomainTree');
}
$scope.getBusDomain = function(stType,parent,varType) {
return {node:[{name:parent}],name:parent, childNode:stType, refType: varType};
}
I am able to fetch values from service but I am not able to populate the recently added value to html page. For that I need to reload the page. Please some one help me out in resolving this issue. Thanks in advance

Resources