Angularjs infinite-scroll for facebook like pagination - angularjs

I want to apply facebook like pagination in my application using angularjs.
how can i find on scroll end event on angularjs.
Currently i am trying with below code but it's don't work.
HTML Code
<div ng-app='myApp' ng-controller='StudController'>
<div infinite-scroll='loadMore()' infinite-scroll-distance='2'>
<div ng-repeat="stud in student.lststudent">
{{stud.rollno}}
</div>
</div>
</div>
JS Script Code
<script>
var myApp = angular.module('myApp', ['infinite-scroll']);
myApp.controller('StudController', function ($scope, $http) {
$scope.loadMore = function () {
var data = $.param({
type: "new",
});
$http({
method: 'POST',
data: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'http://www.apiservice.com/api/StudentList/GetStudent'
})
.success(function (data) {
alert(JSON.stringify(data));
$scope.student= data;
});
};
});
</script>
API Json Response Format
{
"lststudent": [{
"rollno": 12,
"name": "sam"
}, {
"rollno": 15,
"name": "peter"
}],
"status": true,
"message": "success"
}

finally i found solution as below.
I have completed it as per solution in below URL.
http://sroze.github.io/ngInfiniteScroll/demo_async.html
Javascript Code
var mainApp = angular.module("mainApp", ['infinite-scroll']);
myApp.controller('studentcontroller', function ($scope, Reddit, $http) {
$scope.reddit = new Reddit();
myApp.factory('Reddit', function ($http) {
var Reddit = function () {
this.items = [];
this.busy = false;
this.pageno = 1;
};
Reddit.prototype.nextPage = function () {
if (this.busy) return;
this.busy = true;
var data = $.param({
rollno: $("#hdnrollno").data('value'),
pageno: this.pageno,
pagesize: 10
});
NProgress.start();
$http({
method: 'POST',
data: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'http://www.apiservice.com/api/StudentList/GetStudent'
})
.success(function (data) {
scope = data;
var items = data.lststudent;
if (items.length <= 0)
{
NProgress.done();
return;
}
for (var i = 0; i < items.length; i++) {
this.items.push(items[i]);
}
this.pageno = this.pageno + 1;
this.busy = false;
NProgress.done();
}.bind(this));
};
return Reddit;
});
HTML Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngInfiniteScroll/1.2.1/ng-infinite-scroll.min.js"></script>
<div ng-app='myApp' ng-controller='StudController'>
<div infinite-scroll='reddit.nextPage()' infinite-scroll-disabled='reddit.busy' infinite-scroll-distance='1'>
<div ng-repeat="stud in reddit.items">
<span> Rollno </span> {{stud.rollno}}
<span> Student Name</span> {{stud.name}}
</div>
</div>
</div>

Related

code for login authorization using angularjs

I am new to angularjs... i need help in writing code for login authorization with encoded credentials.. i need to do what i have done in jquery.
My jquery code is given below. using java rest services and mysql as backend.
<script type="text/javascript">
$(document).ready(function(){
$(".user_login").click(function(){
var username=$('#uname').val();
var password=$('#pass').val();
function make_base_auth(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "POST",
url: "templates/login",
dataType: 'application/json',
beforeSend: function (xhr){
xhr.setRequestHeader("Authorization" , make_base_auth(username, password));
},
success: function(){
window.location.assign ="welcome.jsp";
},
error: function(data) {
var a = JSON.parse(data.responseText);
$("#login_msg").html("<p style='margin:3px'>" + a.message.text + "</p>");
}
});
});
});
</script>
HTML
<html ng-app="auth">
<div data-ng-controller="AuthController as vm">
// your template
<form>
<input type="text" data-ng-model="vm.username">
<input type="password" data-ng-model="vm.password">
<button data-ng-click="vm.login()">Login</button>
</form
// your template
</div>
</html>
JS auth.js
var app = angular.module('auth', []);
app.controller('AuthController', ['$scope', function($scope){
var vm = this;
vm.login = function() {
function make_base_auth(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
// IMPORTANT, you should move request logic to repositores,
// controller should only do stuff like:
// authService.login(vm.username, vm.password).then(...)
$.ajax
({
type: "POST",
url: "templates/login",
dataType: 'application/json',
beforeSend: function (xhr){
xhr.setRequestHeader("Authorization" , make_base_auth(vm.username, vm.password));
},
success: function(){
window.location.assign ="welcome.jsp";
},
error: function(data) {
var a = JSON.parse(data.responseText);
$("#login_msg").html("<p style='margin:3px'>" + a.message.text + "</p>");
}
});
}
}]);
Use Angular Js functionalities and API's while create web app on angularjs.
You can use jquery(include jquery library) and angularjs have some in build j query functionalities.
https://docs.angularjs.org/api/ng/function/angular.element.
var app = angular.module('exApp', []);
app.controller('authCtrl', ['$scope', 'authService', function($scope, authService){
var self = this;
self.login = function() {
authService.auth(self.username, self.password).then(function(response){
self.message = "logged in successfully";
}, function(error){
self.message = "auth failed";
});
}
}]);
app.service('authService', function($http){
this.auth = function(username, pass){
var postdata = {
method: 'POST',
url: 'templates/login',
headers: {
'Content-Type': 'application/json'
},
data: { 'username': username, 'password':pass }
};
return $http.post(postdata);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="exApp">
<div ng-controller="authCtrl as auth">
<form>
<input type="text" ng-model="auth.username">
<input type="password" ng-model="auth.password">
<button ng-click="auth.login()">Login</button>
</form>
<p style="font-size: 20px;color:red">{{auth.message}}</p>
</div>
</body>

Angularjs goes into infinite loop while firing $http function

My app goes into infinite loop while firing $http get method inside a function
In my controller I am using POST and getting data from API after authorization and displaying it.
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope, $http) {
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
})
.then(function(response) {
$scope.hotels = response.data;
});
$scope.imagePath = function(id) {
console.info(id);
if (id) {
$http({
method: 'GET',
url: 'url=' + id
})
.then(function(response) {
var imgdata = response.data;
console.info(imgdata);
var imgdata1 = imgdata.data.image_name;
return "url" + imgdata1;
});
}
};
});
In my img ng-src I have to call data from another API from the key exterior_image which I am passing in my function but it goes into an infinite loop. Also I know I have to use angular forEach in imgdata1.
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='hotel'></select>
<h1>{{hotel.hotel_name}}</h1>
<p>{{hotel.hotel_description}}</p>
<img ng-src="{{imagePath(hotel.exterior_image)}}">
</div>
Try this in your Controller:
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_name: "Default Value Here",
hotel_description: "Default Value Here",
exterior_image: "Default id here",
image_url: "Default url here"
};
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
}).then(function (response) {
$scope.hotels = response.data;
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: 'url=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "url" + imgdata1;
});
};
});
and this:
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img ng-src="{{current_Hotel.image_url}}">
</div>

$scope variable is not getting updated on view which rendered using $state

Below is app.js file contain myApp module. I am facing issue with $scope variable not updated on view file which is rendered using $state.
I am calling showArticles function on ng-change event from one of view file which got rendered using $state.go statement. This view rendered after user login. All code snap given below. Also facing same issue after AJAX success response $scope not getting updated on view file.
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('settings', {
url: '/settings',
templateUrl: 'templates/setting.html',
controller: 'adminCtrl',
})
.state('profile', {
url: '/profile',
templateUrl: 'templates/profile.html',
controller: 'adminCtrl',
})
.state('account', {
url: '/account',
templateUrl: 'templates/account.html',
controller: 'adminCtrl',
cache: false
})
.state('articleList', {
url: '/articles',
controller: 'adminCtrl',
cache: false,
templateUrl: 'templates/articleList.html',
})
.state('addArticle', {
url:'/addArticle',
templateUrl : 'templates/addArticle',
controller: 'adminCtrl',
cache: false
})
$urlRouterProvider.otherwise('/settings');
});
myApp.run(function($rootScope, $state, $location, AuthenticationService){
//array of route that dont need authentication
var routeThatDontNeedAuth = ['/settings'];
var routeClean = function(route)
{
//alert(route); alert();
if(routeThatDontNeedAuth.indexOf(route) !== -1){ alert('aaa');
return false;
}
else{
return true;
}
}
$rootScope.$on('$stateChangeStart', function(event, next, current){
if(routeThatDontNeedAuth.indexOf($location.url()) < 0)
{
if(!AuthenticationService.isLoggedIn()){
//$state.go('settings');
//alert('not logged in and page is not login page');
}
}
});
});
myApp.factory('AuthenticationService', ['$http', '$state', function($http, $state){
return{
isLoggedIn: function(){ alert('Aut ser called');
$http({
url: 'http://127.0.0.1:8081/cUlI',
method: 'GET'
}).then(function(response){
alert('testtt');console.log(response);
if(!response.data.loggedIn)
{
$state.go('settings');
}
})
}
};
}]);
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
showArticles functions get called on ng-change event from account view:
<div id="main-container" class="col-md-12 container" >
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="main-body">
<div class="content">
<div class="col-md-2"></div>
<div class="col-md-8">
<h2 class="text-center">Article Listing page modified</h2>
<div class="vt-add-article">
<button type="button" ="btn btn-default text-center" ng-click="addArticle();">Add</button>
</div>
<div class="vt-article-list">
{{articleList}}
<br>
{{artLs}} -- exp value
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<div class="col-md-1"></div>
</div>
Main Index .html file :
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Vidarbha Tigers Content Panel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/angularp/router/css/admin.css" />
<script src="/angularp/router/js/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="/angularp/router/js/app.js"></script>
</head>
<body ng-app="myApp" ng-controller="adminCtrl">
<header>
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="vt-header-content col-md-10">
<div class="vt-header-logo">
<!--<img src="/images/logo.jpg" class="img-rounded" alt="Vidarbha Tiger"> -->
</div>
<div class="vt-header-tag"><h2><!--Vidarbha Tigers--></h2></div>
</div>
<div class="col-md-1"></div>
</div>
<hr/>
</header>
<div ui-view></div>
</body>
</body>
</html>
Kindly let me know if I am missing anything in my code. I am new to angular js and facing few issues which are unknown to me
ok, I understand your issue. Your $scope variable is getting reset everytime you call a view. Hence, you dont see any value. You will have to save the value and then retrieve it when your view gets loaded. I have updated your code below, try and let me know if it works or not
SOLUTION 1:
Create one more factory:
myApp.factory('persistService', ['$rootScope', function($rootScope){
var articleList = '';
return{
saveArticleList: function(data) {
articleList = data;
},
getArticleList: function() {
return articleList;
}
};
}]);
Then in your controller include the above service and save the articleList and when you go to your new view, intialize your articleList using the 'persistService' as below :
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'persistService', 'getArticleData', function($scope, $http, $state, getArticleData, persistService){
//Initialize your articleList
$scope.articleList = persistService.getArticleList();
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
persistService.setArticleList('This is a test');
//$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
Let me know if this helps!
EDIT::
SOLUTION 2:
There is another way you can accomplish the same just by making a change in your controller code. See below code:
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
//Initialize your articleList
$scope.articleList = $scope.articleList || {};
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
is the alert that you have put printing the correct value?
Based on my understanding I think you set the articleList on ng-change called in one view file. After that you change state and go to another view file where you expect to see the updated articleList value which you set in the previous view. But, I think what may be happening is that when you navigate to the second view your controller might be getting reloaded and your $scope.articleList gets reset. Try printing the value of articleList before and after you change view.
To prevent this you can try using angular services to save the articleList value

How to transfer data between controllers

I am trying to transfer data between controllers.
So this is my first controller that fetches data first when page loads using http-
function GetController($scope, $http) {
$http.defaults.useXDomain = true;
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data;
}).then(function errorCallback(error) {
})
}
the view looks like-
<div ng-controller="GetController">
<div class="mdl-cell" ng-repeat="product in products">
<img src="{{product.largeImage}}" />
<div class="mdl-card__title">
<h6 class="mdl-card__title-text">{{product.name}}</h6>
</div>
</div>
</div>
</div>
Where now my need is to rebind this HTML with the same request but different parameters. So I created another controller for this job-
function searchProductsController($scope, $http) {
$http.defaults.useXDomain = true;
$scope.searchText = "";
$scope.submit = function () {
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data; //how to bind this with GetController's $scope.products??
}).then(function errorCallback(error) {
});
}
};
What is needed-
I want to bind $scope.products of searchProductsController to GetController's $scope.products so that it renders in view.
I don't have any idea how to do this at the moment as I am very new to angular.
However, I've given a try to create service for transferring purpose but don't really have idea how to integrate it with it.
Edit-
I've edited controller methods as #Varkal suggested using service, Still couldn't get the problem resolved.
var app = angular.module("productsApp", [])
.service("serviceProvider", function ($http) {
this.getDatas = function getDatas(data) {
return $http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: data
})
}
return this
});
function GetController($scope, serviceProvider) {
var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
serviceProvider.getDatas(data).then(function (response) {
$scope.products = response.data.data;
});
}
function searchProductsController($scope, serviceProvider) {
var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
$scope.submit = function () {
serviceProvider.getDatas(data).then(function (response) {
console.log(response.data.data);
$scope.products = response.data.data;
});
}
};
When you need to share things betweens controller, those things should be in a service
For example :
angular.service("datasService", function ($http) {
this.getDatas = function getDatas() {
return $http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
})
}
return this
});
And in your controller :
function GetController($scope, datasService) {
datasService.getDatas().then(function(){
$scope.products = response.data
}
}
This is a very simple example : you can also store your datas in the service, so call $http only once, and add a method to refresh the product list
This is the most "Angular-ly" way of share datas between controllers, but you can also use localStorage (ngStorage can help you here)
If you have 2 views with 2 controllers, it is possible to share the $scope variables(data) between controllers through services and factory.But, the $scope variables are local to the controller itself so set the data to the service or factory to know about that particular variable.I prefer using factory, easy and smooth as butter. If you are using the service or factory in a separate file you need to include the file in index.html.
app.controller('Ctrl1', function($scope, myService, $state) {
$scope.variable1 = "One";
myService.set($scope.variable1);
$state.go('app.thepagewhereyouwanttoshare'); //go to the page where you want to share that variable.
});
app.controller('Ctrl2', function($scope, myService) {
console.log("shared variable " + myService.get());
});
.factory('myService', function() {
function set(data) {
products = data;
}
function get() {
return products;
}
return {
set: set,
get: get
}
})
Also, you can use localstorage for the purpose of sharing data.localStorage comes with angularjs so no need to inject any additional dependency in the controller or app.
In the controller which has to pass data:
localStorage.setItem("products",$scope.products);
In the controller where you to access data:
localStorage.getItem("products");
In your case:
function GetController($scope, $http) {
$http.defaults.useXDomain = true;
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data;
localStorage.setItem("products",$scope.products);
}).then(function errorCallback(error) {
})
}
function searchProductsController($scope, $http) {
$http.defaults.useXDomain = true;
$scope.searchText = "";
$scope.submit = function () {
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data; //how to bind this with GetController's $scope.products??
$scope.productsFromGetController = localStorage.getItem("products");
}).then(function errorCallback(error) {
});
}
};
Using the factory, you need to navigate to the page where you want to get the data after you set it since the data set can be overwritten by another set in another views.
FINAL UPDATE: Using service and factory
<html>
<head>
<title>Angular JS Controller</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "app" >
<div ng-controller="searchProductsController">
<input ng-model="searchText"/>
<button ng-click="setPlace(searchText)">Enter Search id</button>
</div>
<div ng-controller="GetController">
<div ng-repeat="product in products">
<h3>{{product.name}}</h3>
</div>
</div>
</div>
<script>
var app = angular.module('app', []);
app.factory("Service", function () {
var data;
function getdata() {
return data;
}
function setdata(newdata) {
data = newdata;
}
return {
getdata: getdata,
setdata: setdata,
}
}).factory("dataService",function($http){
return{
getComments:function (roomid){
if(roomid==1){
var data = [{"name":"alex","place":"kathmandu"},{"name":"god","place":"seattle"}];
return data;
}
if(roomid==2)
{
var newdata = [{"name":"newname","place":"kathmandu"},{"name":"newname2","place":"seattle"}];
return newdata;
}
}
}
});
app.controller('searchProductsController',function($scope, Service,$http,dataService) {
var data = dataService.getComments(1);
Service.setdata(data);
$scope.setPlace = function (searchText) {
var newdata = dataService.getComments(searchText);
Service.setdata(newdata);
}
})
.controller('GetController',function($scope, Service) {
$scope.$watch(function () {
return Service.getdata();
}, function (value) {
$scope.products = value;
});
})
</script>
</body>
</html>
Update regarding your unworking plunker:
It is closest i can get with the mock of your controller:
http://plnkr.co/edit/p9qY1IIWyzYGLehsIOPr?p=preview

AngularJs server request queue or function is not call

I've subscribed in my controller on socket event.
When some event has come, i need to get some data from server (i try to call lb.get() as a function into some factory).
$scope.counter = 0;
$scope.$on('lEvent', function (event, response) { // socket event
$scope.counter ++;
console.log('counter '+$scope.counter);
lb.get(response[0]).then(function(response){
var Item = {
id: response.id,
mime: response.mime,
name: response.name,
};
$scope.items.push(Item);
console.log("$scope.items"+$scope.items.length);
});
});
// here is a function in my factory
get: function(id) {
deferred = $q.defer();
$http({
method: "post",
url: url,
data: $.param({id: id}),
headers: header
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(data);
});
return deferred.promise;
}
Imagine, i've got 5 socket events, but function lb.get() has called a 4 (or 3) times instead of 5. You can see the result of calling in console:
As you can see, the function lb.get() was called 4 times instead of 5.
I think, i need something like a request queue.
You don't have handle for the error response method get. Maybe in this case, your response is disappear.
You don't need a request queue.
See example on jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleOneController', function($scope, ServiceExample) {
$scope.counter = 0;
$scope.successCounter = 0;
$scope.errorCounter = 0;
$scope.$on('raise.event', function(event, value) {
console.log('counter', $scope.counter);
$scope.counter++;
ServiceExample.get(value).then(function() {
console.log('success response:', $scope.successCounter);
$scope.successCounter++;
}).catch(function() {
console.log('error response:', $scope.errorCounter);
$scope.errorCounter++;
});
});
})
.controller('ExampleTwoController', function($scope) {
$scope.raiseValue = "www.google.com"
$scope.raise = function(val) {
$scope.$emit('raise.event', val);
};
})
.service('ServiceExample', function($http) {
return {
get: function(url) {
return $http({
method: "GET",
url: url
});
}
}
});
.errors {
color: maroon
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ExampleApp">
<div ng-controller="ExampleOneController">
<h3>
ExampleOneController
</h3>
<form name="ExampleForm" id="ExampleForm">
<pre>counter : {{counter}}</pre>
<pre>successCounter: {{successCounter}}</pre>
<pre class="errors">errorCounter: {{errorCounter}}</pre>
</form>
<div ng-controller="ExampleTwoController">
<h3>
ExampleTwoController
</h3>
<form name="ExampleForm" id="ExampleForm">
<input ng-model="raiseValue">
<br>
<button ng-click="raise(raiseValue)" simple>
Send request to "{{raiseValue}}"
</button>
</form>
</div>
</div>
</body>

Resources