I want to increment the data via Button click or scroll.
I have a function which loads the data after button click loadDataQueryDB(param, param, param). With that, I am passing data to MongoDB query.
Well how can I increment my var limit = 50; + 5; after each button click?
Node.js
router.get('/load', function(req, res) {
var skip = 0;
var limit = 50;
var place_val = req.query.place;
var category_val = req.query.category;
var specCategory_val = req.query.specCategory;
if(category_val, specCategory_val, place_val){
Experiences
.find({category : category_val, city:place_val})
.lean()
.skip(skip)
.limit(limit)
.exec(function(err, docs_accommo) {
res.send(docs_accommo);
console.log("First");
});
}
});
Angular.js
app.controller('loadData', ['$scope', '$http', '$window', '$upload', '$rootScope',
function($scope, $http, $window, $upload, $rootScope) {
$scope.loadDataQueryDB = function(place_value, category_value, specCategory_value){
console.log(place_value);
console.log(category_value);
console.log(specCategory_value);
$scope.datafront = [];
var options = {
place : place_value,
category: category_value,
specCategory : specCategory_value
};
$http.get('/load',
{params: options})
.success(function(data) {
$scope.datafront = data;
});
};
});
HTML
<div ng-click="loadDataQueryDB(place, category, specCategory)">
<div ng-repeat="x in datafront | limitTo:? track by x._id" ng-cloak>
{{x}}
</div>
</div>
<button class="btn btn-default" style="float:right; margin-bottom:20px;"/>
Something like the code below, using services and http promises, the data returned form the server its on promise.data.
app.controller('loadData', ['$scope', '$http', '$window', '$upload', '$rootScope','dataService',
function($scope, $http, $window, $upload, $rootScope, dataService) {
$scope.loadDataQueryDB = function(place_value, category_value, specCategory_value){
console.log(place_value);
console.log(category_value);
console.log(specCategory_value);
$scope.datafront = [];
var params = {
place : place_value,
category: category_value,
specCategory : specCategory_value
skip : $scope.skip,
limit : $scope.limit
}
dataService.getData(params).then(function(promise){
$scope.dataFront = promise.data;
//Increment the limit by ten
$scope.limit =+ 10;
})
};
});
app.module('dataService').factory('dataService',['$http',function ($http) {
var service = {};
factory.getData= function (params) {
var promise = $http({
method: 'GET',
url: '/load',
params: params
});
return promise;
}
return service;
}]);
You should have only the gets that return views on the router and the rest of the get and post calls on a service, at least I develop like that and its more confortable.
Related
I am trying to route my page to another page once the controller is accessed but its not working. I can route the first two pages but the third one is not working. Can someone help me on this.
This is my routing code:
$routeProvider', function ($routeProvider) {
$routeProvider.
when('/category', {
//templateUrl : 'js/partials/course-list.html',
controller : 'CategoryController'
}).
when('/category/:categoryid', {
templateUrl : 'js/partials/film-list.html',
controller : 'MovieController'
}).
when('/actor/:filmid', {
templateUrl : 'js/partials/actor-list.html',
controller : 'ActorController'
}).
otherwise({
redirectTo : '/'
});
}
Currently my ActorController is not working. Once i click on the movies it should show the actor of the films but in my case its not working
This is my partial html file for the movie-list.html
<section>
<h3>{{movieCount}}</h3>
<table>
<tr data-ng-repeat="movie in movies" data-ng-click="selectFilm($event,movie)" style="cursor: pointer;">
<td>{{movie.title}}</td>
</tr>
<strong>{{successMessage}}</strong>
</table>
And this is my controller code
).controller('ActorController',
[
'$scope',
'dataService',
'$routeParams',
function ($scope, dataService, $routeParams){
$scope.actors = [ ];
$scope.actorCount = 0;
var getActors = function (moviecode) {
dataService.getActors(moviecode).then(
function (response) {
$scope.actorCount = response.rowCount + ' actors';
$scope.actors = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "Actor Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
// only if there has been a courseid passed in do we bother trying to get the students
if ($routeParams && $routeParams.filmid) {
console.log($routeParams.filmid);
getActors($routeParams.filmid);
}
}
]
)
This is the selectFilm() code from the MovieController
$scope.selectedFilm = {};
$scope.selectFilm = function ($event,movie) {
$scope.selectedFilm = movie;
$location.path('/actor/' + movie.film_id);
}
This is the movie controller code
).controller('MovieController',
[
'$scope',
'dataService',
'$routeParams',
'$location',
function ($scope, dataService, $routeParams, $location){
$scope.movies = [ ];
$scope.movieCount = 0;
var getMovies = function (moviecode) {
dataService.getMovies(moviecode).then(
function (response) {
$scope.movieCount = response.rowCount + ' movies';
$scope.movies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "Movies Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
$scope.selectedFilm = {};
$scope.selectFilm = function ($event,movie) {
$scope.selectedFilm = movie;
$location.path('/actor/' + movie.film_id);
// $window.location.href = '/actor/' + movie.film_id
console.log(movie.film_id);
}
// only if there has been a courseid passed in do we bother trying to get the students
if ($routeParams && $routeParams.categoryid) {
console.log($routeParams.categoryid);
getMovies($routeParams.categoryid);
}
}
]
)
I solved the problem by myself wher first of all the $location variable was not defined in the function and later on the movie object dont have the film_id so I had to readjust my SQL query to make it work. After changing the SQL query i can route my page now.
I have a form that is posting /api/tradelink but it doesn't send any body or data with it.
HTML :
<form ng-submit="sendTradelink()">
<md-input-container class="md-accent">
<label>Enter your tradelink</label>
<input ng-model="tradelink">
</md-input-container>
<md-button type="submit" class="md-raised md-accent">Send</md-button>
</form>
Services :
.factory('Auth', ['$http', '$api', '$window', function ($http, $api, $window) {
var authFactory = {};
authFactory.authenticate = function(){
$http.post($api.url + 'auth')
.successs(function(url){
$window.location.href = url;
});
};
authFactory.send = function () {
return $http.post($api.url + 'tradelink');
};
return authFactory;
}]);
Controller ;
.controller('AppCtrl', ['$scope', 'Auth', '$location', '$cookies', function ($scope, Auth, $location, $cookies) {
var sidTemp = 'needtomakeitanewvalue';
$scope.checklogin = function () {
$scope.sid = $cookies.get('sid2');
console.log($scope.sid);
}
$scope.sendTradelink = function () {
Auth.send($scope.tradelink)
.success(function (res) {
$scope.sidTemp = 'needtomakeitanewvalue';
$cookies.put('sid2', sidTemp);
$location.path('/');
});
}
$scope.auth = function () {
Auth.authenticate();
}
}])
Server side holding api request, nothing inside req.body or req.params. Both show as empty objects.
api.post('/tradelink', function(req, res){
console.log(req.user.steamId);
console.log(req.params);
console.log(req.body);
res.json({
success: true,
message: 'tradelink received'
})
});
Check the Angular docs for $http.post
You are calling Auth.send($scope.tradelink), but your authFactory.send() function needs to accept this tradelink value and then be used as a data param to $http.post()
So:
authFactory.send = function (tradelink) {
return $http.post($api.url + 'tradelink', {tradelinkId: tradelink });
};
This may be very basic but I'm new to angular and am stumped. I have 2 views that need to access the same user input data from a form. Each view has it's own controller.
Here's where I'm at:
JAVASCRIPT
.config(function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl : 'view1.html',
controller: 'ctrl1'
})
.when('/view2', {
templateUrl : 'view2.html',
controller : 'ctrl2'
})
})
//SERVICE TO HOLD DATA
.service('Data', function() {
return {};
})
//CONTROLLER 1
.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
$scope.data = Data;
var $scope.initValue = function() {
$scope.data.inputA = 0; //number
$scope.data.inputB = 0; //number
}
var $scope.onSubmit = function() {
$scope.data.result = $scope.data.inputA + $scope.data.inputB;
}
}])
//CONTROLLER 2
.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
$scope.data = Data;
}
}])
HTML (view2.html)
<p>Result is {{data.result}}</p>
This displays nothing, I'm thinking it's because the service or controller resets the values when changing views? Am I just totally wrong for using a service to do this?
You have to update the data in the service so that it can be used in another controller:
// define a var container in the service
// you can make it neat by creatin a getter and setter
.service('Data', function() {
var value = null;
var setValue = function(val) {
this.value = val;
};
var getValue = function() {
return this.value;
};
return {
value: value,
setValue: setValue,
getValue: getValue,
};
}
Then in controller 1 you can set the value in the service like so:
//CONTROLLER 1
.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
$scope.inputA = 0;
$scope.inputB = 0;
$scope.onSubmit = function() {
$scope.result = $scope.inputA + $scope.inputB;
Data.setValue($scope.result);
}
}])
And in controller 2 you can use the value like so:
//CONTROLLER 2
.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
$scope.value = Data.getValue();
}])
Hope this will help.
Hi guys I've been trying for a while now to sort data braught from openweathermap.org using the api provided by the site and the ng-repeat feature in angularjs. for some reason i can't seem to get it to work... what I'm trying to do is to first display all of the gathered data and then sort it using the input field.
Javascript
var app = angular.module('weatherApp', []);
app.controller('weatherController', function($scope, $http) {
$http.jsonp('http://api.openweathermap.org/data/2.5/weather', { params : {
q : $scope.city,
units : $scope.units,
callback: 'JSON_CALLBACK',
APPID: $scope.id
}}).success(function(data){
$scope.data = data;
});
$scope.units = 'metric';
$scope.id = 'e08f9689f06c1b6eddb44396c749eb54';
$scope.reset = function(){
return $scope.city = "";
};
});
HTML
<div ng-app="weatherApp" ng-controller="weatherController">
<input ng-model="city.name" placeholder="City" />
<button ng-click="reset()">Reset</button>
<ul>
<li ng-repeat=" x in data | filter : city">
{{x.name}}
</li>
</ul>
You could try to set the $scope.id and $scope.units before calling $http.jsonp. Seems to me that the values are used in the parameters before being set. Try changing this to:
var app = angular.module('weatherApp', []);
app.controller('weatherController', function($scope, $http) {
$scope.units = 'metric';
$scope.id = 'e08f9689f06c1b6eddb44396c749eb54';
$http.jsonp('http://api.openweathermap.org/data/2.5/weather', { params : {
q : $scope.city,
units : $scope.units,
callback: 'JSON_CALLBACK',
APPID: $scope.id
}}).success(function(data){
$scope.data = data;
});
$scope.reset = function(){
$scope.city = '';
};
});
I already have seem other topics with this kind of issue, but no one could help me... So here is my issue:
I have a navbar with a button for search, this buttons makes and get request from a webservice and returns a json object which must be apply to fill an table list. The problem is, my button and my table are in separated controllers, and it does work like I expected.
var app = angular.module('clientRest', []).controller('lista', ['$scope', 'loadLista', function($scope, loadLista) {
$scope.contatos = loadLista.getContatos();
}]).controller('pesquisa', ['$scope', '$http', 'loadLista', function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato").success(function(response) {
loadLista.setContatos(response);
});
};
}]).service('loadLista', function() {
var contatos = [];
return {
getContatos: function() {
return contatos;
},
setContatos: function(c) {
contatos = c;
}
};
});
My code...
When I call listar() from pesquisa controller I need to send received data to $scope.contatos from lista controller to make my ng-repeat work, everything with a single click.
How can I do it?
Thanks everyone
Better to use a service to share data between two controllers / modules as this might be the best approach. You can refer the code segment given below to understand the concept.
angular.module('app.A', [])
.service('ServiceA', function() {
this.getValue = function() {
return this.myValue;
};
this.setValue = function(newValue) {
this.myValue = newValue;
}
});
angular.module('app.B', ['app.A'])
.service('ServiceB', function(ServiceA) {
this.getValue = function() {
return ServiceA.getValue();
};
this.setValue = function() {
ServiceA.setValue('New value');
}
});
In order to trigger the data receipt event, you may use
Broadcast / emit messages - with #broadcast / #emit
An angular promise with a call back
Controller initiation function to reload the previously read information from a service
.controller('MyController', function($scope, ServiceA) {
$scope.init = function() {
$scope.myValue = ServiceA.getValue();
};
// Call the function to initialize during Controller instantiation
$scope.init();
});
Use $rootScope.$emit to emit a change event when setting the variable and use $on to get the value in the lista controller. I used customListAr here just to demostrate a button click. Does this help?
var app = angular.module('clientRest', [])
.controller('lista', ['$scope', 'loadLista', '$rootScope',
function($scope, loadLista, $rootScope) {
console.log(loadLista);
$scope.contatos = loadLista.getContatos();
$rootScope.$on('change', function() {
$scope.contatos = loadLista.getContatos();
});
}
])
.controller('pesquisa', ['$scope', '$http', 'loadLista',
function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato").success(function(response) {
loadLista.setContatos(response);
});
};
$scope.customListAr = function() {
loadLista.setContatos(["item 1" , "item 2", "item 3"]);
}
}
])
.service('loadLista', ['$rootScope',
function($rootScope) {
var contatos = [];
return {
getContatos: function() {
return contatos;
},
setContatos: function(c) {
contatos = c;
$rootScope.$emit('change');
}
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="clientRest">
<div ng-controller="lista">
<ul>
<li ng-repeat="a in contatos">{{a}}</li>
</ul>
</div>
<div ng-controller="pesquisa">
<button ng-click="customListAr()">Click Me</button>
</div>
</div>
Your problem is that when you do $scope.contatos = loadLista.getContatos(); you are setting a static value, and angular is unable to effectively create a watcher for that object because your setContatos method is creating a new object each time. To get around this, have the controller's scope hold a reference to the parent object and then it will automatically have a watcher on that object.
var app = angular.module('clientRest', [])
.controller('lista', ['$scope', 'loadLista', function($scope, loadLista) {
$scope.contatos = loadLista.contatos;
}])
.controller('pesquisa', ['$scope', '$http', 'loadLista', function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato"
).success(function (response) {
loadLista.contatos.data = response;
});
};
}])
.service('loadLista', function() {
var lista = {
contatos: {},
};
return lista;
});
// view:
<ul>
<li ng-repeat="contato in contatos.data">
{{ contato }}
</li>
</ul>