Meteor application crashing while calling last message - angularjs

In one of controller I'm trying to list all online users and their last message. But the browser is unresponsive while running the below code.
In app.js
angular.module('jaarvis').controller('OnlineUsersCtrl', ['$scope', '$meteor', function ($scope, $meteor) {
$scope.$meteorSubscribe('users');
$scope.$meteorSubscribe('chats');
var query = {};
query['status.online'] = true;
var online = $meteor.collection(function(){
return Meteor.users.find(query, {fields: {'_id':1, 'profile.name':1, 'status.online':1}});
});
$scope.onlineusers = online;
$scope.getLastMessage = function(userId) {
var query = {};
query['uid'] = userId;
var lastMessage = $meteor.collection(function(){
return Chats.find({'uid':userId}, {fields: {'content':1}}, {sort: {'_id': -1}, limit: 1});
});
return lastMessage;
};
}]);
In HTML
<div class="list">
<a class="item item-avatar" href="/onetoonechat/{{onlineuser._id}}" ng-repeat="onlineuser in onlineusers">
<img src="venkman.jpg">
<h2>{{onlineuser.profile.name}}</h2>
<p>{{ getLastMessage(onlineuser._id) }}</p>
</a>
</div>
Correct if there is any mistake in my code or provide alternative solution.

Related

View results of a search in the same View AngularJS

First sorry for my bad english. I'm developing an app to be able to study and was putting everything on the controller, all queries and all. But then I decided to pass it to a service (vi which is the right to do so), only when I queries for my search service just stopped working.
In the template I list all registered categories and it has an input, which makes the search all registered establishments in the DB. I wish that when you do a search, the list simply update with a new, only listing the results of this search.
When I try to do a search, the following error appears:
Object {message: "sqlite3_bind_null failure: bind or column index out of range", code: 0}
And so are all related to this template code and the search:
Service.js
app.service('Market', function($cordovaSQLite, DBA) {
var self = this;
self.allCategories = function() {
return DBA.query("SELECT id, category_name FROM tblCategories")
.then(function(result){
return DBA.getAll(result);
});
}
self.searchAll = function(nameSearch) {
var parameters = [nameSearch];
return DBA.query("SELECT id, place_name FROM tblPlaces WHERE place_name LIKE '%(?)%'", parameters)
.then(function(result) {
return DBA.getAll(result);
});
}
return self;
})
Controller.js
app.controller('CategoriesCtrl', function($scope, Market) {
$scope.categories = [];
$scope.categories = null;
$scope.items = [];
$scope.items = null;
var nameSearch = '';
$scope.searchkey = '';
$scope.myClick = function (search) {
nameSearch = search;
console.log(nameSearch);
$scope.searchResult = function(nameSearch) {
Market.searchAll(nameSearch).then(function(items) {
$scope.items = items;
console.log(items);
});
}
$scope.searchResult();
};
$scope.listAllCategories = function() {
Market.allCategories().then(function(categories) {
$scope.categories = categories;
});
}
$scope.listAllCategories();
})
Categories.html
<div class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios-search placeholder-icon"></i>
<input type="text" placeholder="Search" name="key" autocorrect="off" ng-model="searchkey">
</label>
<button class="button" ng-click="myClick(searchkey)">Buscar</button>
</div>
<ion-list>
<ion-item ng-repeat="category in categories">{{category.category_name}}</ion-item>
</ion-list>

Output image from RESTful Service Angular

I am new to Angular so to get to grips with it I have been working with a Dummy RESTful service. Right now I have managed to pull the image URL and then push it into an array.
I would like to output this array as an image when the "ng-click" directive is fired.
Any guidance or help would be much appreciated.
<p ng-click="outputImageData()">click me</p>
<ul>
<li ng-repeat="photo in photos">
{{ image }}
</li>
</ul>
myApp.factory('getImages', function($http) {
var imageService = {
async: function(id) {
var promise = $http.get('https://jsonplaceholder.typicode.com/photos/1').then(function(response) {
return response.data;
})
return promise;
}
};
return imageService;
});
myApp.controller("outputImages", function($scope, getImages) {
var photos = [];
$scope.outputImageData = function() {
getImages.async().then(function(data) {
var photoId = data.url;
photos.push(photoId);
console.log(photos);
})
}
});
Thanks
I've been using angularjs but generally as a developer, I'm just started so bear with me, please.
I think something like this would work:
<p ng-click="updateImageData()">click me</p>
<ul>
<li ng-repeat="photo in photos">
<img src="{{photo.url}}">
</li>
</ul>
myApp.factory('getImages', function($http) {
var imageService = {
async: function() {
var promise = $http.get('https://jsonplaceholder.typicode.com/photos/');
return promise;
}
};
return imageService;
});
myApp.controller("outputImages", function($scope, getImages) {
$scope.photos = [];
$scope.updateImageData = function() {
getImages.async(photoId).then(function(data) {
$scope.photos = data;
console.log(photos);
})
}
});

AngularJs requires page refresh after API call

I am writing an angularjs app. The requirement is to display the user's data once the user logs in. So when an user successfully logs in, he/she is routed to the next view. My application is working fine upto this point. Now as the next view loads I need to display the existing records of the user. However at this point I see a blank page, I can clearly see in the console that the data is being returned but it is not binding. I have used $scope.$watch, $scope.$apply, even tried to call scope on the UI element but they all result in digest already in progress. What should I do? The page loads if I do a refresh
(function () {
"use strict";
angular.module("app-newslist")
.controller("newsController", newsController);
function newsController($http,$q,newsService,$scope,$timeout)
{
var vm = this;
$scope.$watch(vm);
vm.news = [];
vm.GetTopNews = function () {
console.log("Inside GetTopNews");
newsService.GetNewsList().
then(function (response)
{
angular.copy(response.data, vm.news);
}, function () {
alert("COULD NOT RETRIEVE NEWS LIST");
});
};
var el = angular.element($('#HidNews'));
//el.$scope().$apply();
//el.scope().$apply();
var scpe = el.scope();
scpe.$apply(vm.GetTopNews());
//scpe.$apply();
}
})();
Thanks for reading
you don't show how you're binding this in your template.. I tried to recreate to give you a good idea.
I think the problem is the way you're handling your promise from your newsService. Try looking at $q Promises. vm.news is being updated by a function outside of angular. use $scope.$apply to force refresh.
the original fiddle is here and a working example here
(function() {
"use strict";
var app = angular.module("app-newslist", [])
.controller("newsController", newsController)
.service("newsService", newsService);
newsController.$inject = ['$http', 'newsService', '$scope']
newsService.$inject = ['$timeout']
angular.bootstrap(document, [app.name]);
function newsController($http, newsService, $scope) {
var vm = this;
vm.news = $scope.news = [];
vm.service = newsService;
console.warn(newsService)
vm.message = "Angular is Working!";
vm.GetTopNews = function() {
console.log("Inside GetTopNews");
newsService.GetNewsList().
then(function(response) {
$scope.$apply(function() {
$scope.news.length > 0 ? $scope.news.length = 0 : null;
response.data.forEach(function(n) {
$scope.news.push(n)
});
console.log("VM", vm);
})
}, function() {
alert("COULD NOT RETRIEVE NEWS LIST");
});
};
}
function newsService($timeout) {
return {
GetNewsList: function() {
return new Promise(function(res, rej) {
$timeout(function() {
console.log("Waited 2 seconds: Returning");
res({
data: ["This should do the trick!"]
});
}, 2000);
})
}
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
<body>
<div class="main">
<div class="body" ng-controller="newsController as vm">
Testing: {{ vm.message }}
<br>{{ vm.news }}
<br>{{ vm }}
<br>
<button class="getTopNewsBtn" ng-click="vm.GetTopNews()">Get News</button>
<br>
<ul class="getTopNews">
<li class="news-item" ng-repeat="news in vm.news track by $index">
{{ news | json }}
</li>
</ul>
</div>
</div>
</body>

Increasing a vote (in a list of saved URLs) doesn't work

I have a list of URLs saved in a firebase DB, and I'm trying to simply add a count next to each url, so that users can like them. My $scope.increase function tries to serve that purpose but there must be something wrong, it should increase the count on click and also update the database. Can anyone help?
HTML
<li ng-repeat="url in urls | filter:todoSearch" class="list-item">
<div class="row">
<div class="col-md-8 link-col">
<a href="{{url.title}}" class="link">
<p class="title">{{url.name}}</p>
<p class="url">{{url.title}}</p>
</a>
<p ng-model="mvLikes" ng-click="increase($index)">0</p>
</div>
</div>
</li>
JS
var urlFire = angular.module("UrlFire", ["firebase"]);
function MainController($scope, $firebase) {
$scope.favUrls = $firebase(new Firebase('https://lloydyapp.firebaseio.com/'));
$scope.urls = [];
$scope.favUrls.$on('value', function() {
$scope.urls = [];
var mvs = $scope.favUrls.$getIndex();
for (var i = 0; i < mvs.length; i++) {
$scope.urls.unshift({
name: $scope.favUrls[mvs[i]].name,
title: $scope.favUrls[mvs[i]].title,
likes: $scope.favUrls[mvs[i]].likes,
key: mvs[i]
});
};
});
$scope.increase = function(index) {
$scope.mvLikes += 1;
var mvLikes = $scope.mvLikes;
var mv = $scope.urls[index];
var updateUrlRef = buildEndPoint(mv.key, $firebase);
updateUrlRef.$set({
likes: mvLikes
});
}
....
function buildEndPoint(key, $firebase) {
return $firebase(new Firebase('https://lloydyapp.firebaseio.com/' + key));
}

Initialise AngularJS service - factory on the document load

Sorry for a very stupid question but I just started working with AngularJS and OnsenUI.
I have got a service to get a data from SQLite:
module.factory('$update', function () {
var update = {};
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM event_updates', [], function (tx, results) {
var rows = results.rows;
update.items = [];
if (!rows.length) {} else {
for (var index = 0; index < rows.length; index++) {
update.items.push({
"title": rows.item(index).title,
"date": rows.item(index).date,
"desc": rows.item(index).desc
});
}
}
}, function (error) {
console.log(error);
});
});
return update;
});
And a controller which is using the data:
module.controller('UpdatesController', function ($scope, $update) {
$scope.items = $update.items;
});
As soon as my page is loaded the content is not displayed and I need to click twice to call a page with the code below to see the content:
<ons-list ng-controller="UpdatesController">
<ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in items" ng-click="showUpdate($index)">
<div class="list-item-left">
</div>
<div class="list-item-right">
<div class="list-item-content">
<div class="name">{{item.title}}</div> <span class="desc">{{item.desc}}</span>
</div>
</div>
</ons-list-item>
</ons-list>
Can anybody help how can I initialise the controller as soon as page is loaded with all content. Sorry if it is a stupid question but I am really struggling. Appreciate your help a lot.
You could store the result of the request in the factory and retrieve those instead.
module.factory('$update', function () {
var update = {};
var requestValues = function(){ // store the results of the request in 'update'
// Your db.transaction function here
}
var getUpdates = function(){ // retrieve the values from 'update'
return update;
}
return{
requestValues : requestValues,
getUpdates : getUpdates
}
});
And then in you controller:
module.controller('UpdatesController', function ($scope, $update) {
$update.requestValues();
$scope.items = $update.getUpdates();
});
You could then get the values from anywhere in you solution (by using $update.getUpdates) without having to make an extra http request.

Resources