Persistence storage in ForerunnerDB not working properly - angularjs

I am using ForerunnerDB - a NoSQL JSON Document DB for creating a data store on the client (web). This particular library offers a persistence storage option. However, there seems to be something wrong with it. I have included my code below:
App:
(function(){
angular.module("TestApp", ['ui.router', 'LocalStorageModule', 'forerunnerdb']);
})();
Controller:
(function(){
angular.module("TestApp")
.controller("FetchGroupsController", function(clientStore, $scope, $http){
clientStore.getTable("groups").load(function (err, tableStats, metaStats) {
if (err) {
// Load operation was unsuccessful
console.error("error in pulling collection " + name);
console.error(err)
}
else{
//there is persisted data corresponding to the requested table
if(tableStats.foundData && tableStats.rowCount > 0){
controller.groups = clientStore.fetchRecords("groups"); //returns an array of objects
console.log("User has " + tableStats.rowCount + " groups");
console.log(controller.groups);
}
else{//no table for group data persisted */
$http({ method: "POST", url: "api/groups/index"})
.success(function(data, status){
//TODO: handle the activation code
if(status == 200){
delete data["debug"]; //deleting an unnecessary object from response data
clientStore.addList("groups", data);
controller.groups = clientStore.fetchRecords("groups");
console.log(controller.groups);
clientStore.getTable("groups").save();
}
else if(status == 403){ //forbidden
controller.messages = data;
}
else if(status == 401){ //error
controller.errors = data;
}
})
;
}
}
});
});
})();
Service:
angular.module("TestApp")
.factory('clientStore', function($fdb, $http, localStorageService){
var clientDB = null;
var factory = {};
clientDB = $fdb.db("testDB");
factory.getDB = function(){
return clientDB;
};
factory.createTable = function(name, pk){
if(pk != false){
return clientDB.collection(name, {primaryKey : pk});
}
return clientDB.collection(name);
};
factory.resetTable = function(name){
clientDB.collection(name)._data = [];
clientDB.collection(name).save();
};
factory.getTable = function(name){
return clientDB.collection(name);
};
factory.add = function(name, record){ //insert a single object
clientDB.collection(name).insert(record/*, function(result){
console.warn(result);
}*/);
};
factory.addList = function(name, records){ //insert a list of objects
for (record in records){
clientDB.collection(name).insert(records[record]);
}
};
factory.fetchRecords = function(name){
return clientDB.collection(name)._data;
};
return factory;
});
View:
<div ng-repeat="group in fetchGrpsCtrl.groups" class="row">
<div class="col-md-12">
<div class="groups" id="grp-#{{group.id}}" ng-click="fetchGrpsCtrl.setGroup(group)">
<div class="details">
<h5> #{{group.title}}</h5>
</div>
</div>
</div>
</div>
The problem is that the variable controller.group is null in the view, but in the controller, I am getting the expected value when I log it (line 15) out to the console. I thought maybe it was a problem of scope and that the changes made to the variable inside the callback were not being picked up in the view. But that is the not the case because I commented out the line
clientStore.getTable("groups").save();
and ran it again and the view was updated perfectly as expected. I cannot figure out why the save() function is erasing the controller.groups variable in the view but is logged out perfectly in the controller.

You are using ForerunnerDB incorrectly. It includes an AngularJS plugin that makes using it with AngularJS very easy, but instead you've written a wrapper of your own that hooks onto the _data property of a collection (something that you shouldn't do because that property is managed internally by ForerunnerDB and can be destroyed and re-created meaning you will have an incorrect reference to an object that might no longer be used by a collection).
Instead you should use ForerunnerDB in AngularJS as described in the documentation: https://github.com/Irrelon/ForerunnerDB#angularjs-and-ionic-support
ForerunnerDB includes a helper method called "ng()" that allows you to correctly link data from a collection to your view's scope.
Also, when using third party javascript libraries, properties with an underscore are generally considered "private" and should not be accessed directly. You should use an accessor method (such as .find() in ForerunnerDB's case) to access data instead. Usually a property that starts with an underscore is a good indication that it is private (not all libraries and programmers follow this convention but many do).

Related

Why ng-repeate object not getting updated?

This is the function which load listings from server. Initially listings are displayed but when gets null response on applying filter, it still shows previous result and not clearing previous listings.
$scope.browseListing = function (strURL) {
$scope.CurrentTab = strURL;
$scope.getURL(strURL);
$http.post($scope.URL)
.then(function (response) {
if (response.data != 'null') {
$scope.Data = response.data;
$scope.TotalListingCount = $scope.Data.length;
$window.alert('Result is not null');
}
else {
$scope.TotalListingCount = '0';
$window.alert('Result is null');
$scope.Data = [];
}
}, function (response) {
$log.info(response);
});
};
Edited
How do I solve this so that on empty response previous listings gets cleared and shows no listings?
May be your scope does not update. Please try this below ( it's not 100% good approach, But at this time you can solve your issue)
if(!$scope.$$phase) {
$scope.$apply(
$scope.Data = [];
);
}
$scope.TotalListingCount = '0';
$window.alert('Result is null');
and please check your console having any error.
Update :
try another way like this (declare empty object globally)
.then(function (response) {
$scope.TotalListingCount = '0';
$scope.Data = [];
if (response.data != 'null') {
$scope.Data = response.data;
$scope.TotalListingCount = $scope.Data.length;
$window.alert('Result is not null');
}
else {
$window.alert('Result is null');
}
}
It's does not works well, then please share your filter code. Bcs the problem should be there.
The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-view, ng-controller, directive with scope: true, directive with transclude: true.
So, use $parent with 'ng-repeate' to reference to parent scope instead of using newly created scope byng-repeat` as-
<tr ng-repeat="listing in $parent.Data | orderBy : sortColumn : SortDirection">
After adding $parent in ng-repeat to scope property in UI it updates UI as per changes.
Here is full description of scope

Passing the URL/route parameter from laravel and using in angular

I am new to Laravel 5 and angular.
I am using Laravel routing for traversal and backend operations and angular for just UI operations like fetching data and binding UI grid, etc.
I have following route defined in routes.php file below
routes.php
Route::pattern('clientid', '[0-9]+');
//used for AJAX call from angularjs and populating ui-grid
Route::get('getclients/{clientid?}', 'ClientController#getClients');
//used for displaying Laravel view with ui-grid
Route::get('client/{clientid?}', 'ClientController#showClients');
Please find the angular files:
app.js
var appClients = angular.module('getclients', ['clientsService', 'ui.grid', 'ui.grid.exporter', 'ui.grid.selection']);
clientController.js
appClients.controller('ClientsController', ['$scope', '$http', 'Client', '$interval', '$q', function ($scope, $http, Client, $interval, $q) {
/* Defining UI grid options*/
.
.
/* Calling service to fill the grid*/
Client.get(clientid)
.success(function (data, status, headers, config) {
if (data.length > 0) {
$scope.gridOptions.data = data;
}
});
}
clientsService.js
angular.module('clientsService', [])
.service('Client', function ($http) {
return {
// Get all the photos
get: function (clientid) {
if (clientid !== '') {
return $http.get('/myproject/public/getclients/' + clientid);
}
else {
return $http.get('/myproject/public/getclients/');
}
}
}
});
/*
**Note:**
Have already defined route in routes.php for using the same above:
Route::get('getclients/{clientid?}', 'ClientController#getClients');
*/
EXAMPLE:
Step 1:
Say I am hitting URL: http://<domain>/public/myproject/client/2
The following route would catch it and redirect to view where the ui-grid is present
Route::get('client/{clientid?}', 'ClientController#showClients');
Step 2:
Now, somehow need to figure out how to pass that **2** to angular so that I could pass that parameter while making ajax call and get grid data
I am confused as to how we could use the the url parameter from Laravel in angular?
I reckon that I am missing some concept or doing something wrong here.
Could anyone help me out?
Just a workaround to make it work with angular and without jquery.
From routes.php, the control is transferred to showClients action in ClientsController.php
ClientsController.php (Laravel Controller):
Passed the variable to Laravel view from controller using following statement:
public function showClients($clientid = '') {
return view('masters.clients', compact('clientid'));
}
Clients.php (Laravel View)
Added clientidmodel as ng-model and initialized it with passed clientid from Laravel controller using ng-init
<div ng-app="">
<div ng-controller="ClientsController">
<input type="text" name="txtClientId" ng-model="clientidmodel" style="display: none;" ng-init="clientidmodel = '{!!$clientid!!}'"/>
</div>
</div>
clientController.js
Added the watch to the angular model so that we can capture the initial value passed.
$scope.$watch("clientidmodel", function () {
Client.get($scope.clientidmodel)
.success(function (data, status, headers, config) {
if (data.length > 0) {
$scope.gridOptions.data = data;
}
});
});
Not sure whether this is the efficient way but as of now got the things working with this workaround.
Please let me know in case of any better way to approach the same.
You can achieve this in jquery by
var pathname = window.location.href;
var lastItem = pathname.split("/").pop(-1);
Note : Here you will get the last element
i.e.,
If your url is like yourapp.com/app#/product/15 then the script will return 15. That's the last element after / . You can change this according to your wish.
Then you can pass the value directly inside your Laravel Controller.
$.ajax({
type: "POST",
dataType: 'text',
crossOrigin : true,
data: {param : lastItem},
url: serviceUrl+'/getReceipeDetails',
})
.done(function( data ) {
var result = jQuery.parseJSON(data);
if(result.success==1)
{
$(".yourresult").html('Controller return success');
}
else
{
$(".yourresult").html('Controller return failure');
}
})
.fail( function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
});

AngularJS Service to Service with a delay

I am currently facing a problem with my project's design.
I am using angularjs framework and my task is to provide a translations for a webpage, but the translations need to be provided form the xml file o the BE side.
So since I#ve found out that angulars i18n is configurable on the FE side i had to use another strategy.
I've decided to make a service which fetches the data during a resolve period before everything else is loaded:
app.factory('dictionaryService', ['$http', '$rootScope', function ($http, $rootScope) {
return {
getDictionary: function (defaultLanguage) {
var chosenLanguage = null;
if (angular.isUndefined($rootScope.defaultLanguage) || $rootScope.defaultLanguage == null) {
chosenLanguage = defaultLanguage;
$rootScope.defaultLanguage = chosenLanguage;
} else {
chosenLanguage = $rootScope.defaultLanguage;
}
var translation = new Array();
translation[chosenLanguage] = new Array();
return $http.get('Translation/GetCurrentDictionary/', {
params: {
language: chosenLanguage
}
});
},
GetLanguagesSetup: function () {
return $http.get('Translation/GetLanguagesSetup/');
}
}
}]);
and then resolve it as follows:
$routeProvider.when("/diagnose", {
controller: "diagnoseCtrl",
templateUrl: "/app/views/diagnose.html",
resolve: {
startupData: function (dictionaryService, $q) {
var def = $q.defer();
var translation = new Array();
var startupData = new Array();
var defaultLanguage = "EN";
var dict = dictionaryService.getDictionary(defaultLanguage).then(function (JSONData) {
var keys = Object.keys(JSONData.data.data);
var chosenLanguage = JSONData.data.lang;
translation[chosenLanguage] = {};
for (i = 0; i < keys.length; i++) {
translation[keys[i]] = JSONData.data.data[keys[i]];
}
startupData['translations'] = translation;
def.resolve(startupData);
}).catch(function (e) {
console.log("Translation fetching exception, " + e);
return $q.reject(e);
});
return def.promise;
}
}
});
So as you can see I am storing my fetched translations in a startupData. Then in a controller which is using it I am assigning this data to the $rootScope. It seems already here as a not the best solution, but I could not come up with a different one
Then I have created a translation service which gets the direct translation text:
app.factory('translationService', ['$rootScope', '$http', function ($rootScope, $http) {
var translations = null;
return {
getText: function (key) {
if ($rootScope.cachedTranslations == undefined) {
return key;
}
var result = $rootScope.cachedTranslations[key];
if (result == null) {
return key;
} else {
return result;
}
}
}
}]);
The biggest problem with this solution is, that I am not using promises, but I do not want to make an http query to BE for each translation.
The other problem is with the html template provided by the designers:
<body ng-controller="mainController">
<loading-screen ng-show="!isDataLoaded"></loading-screen>
<div id="header" class="headerView" ng-controller="headerController" ng-show="isDataLoaded">
some header stuff
...
<button ng-bind="option1" ng-click="redirectTo('#subpage1')"></button>
<button ng-bind="option2" ng-click="redirectTo('#subpage2')"></button>
<button ng-bind="option3" ng-click="redirectTo('#subpage3')"></button>
<button ng-bind="language" ng-if="availableLanguages.length > 1" ng-repeat="language in availableLanguages" ng-click="setLanguage(language)"></button>
</div>
</div>
<
<div id="content" ng-view ng-show="isDataLoaded">
</div>
<footer id="footer" class="footer" ng-show="isDataLoaded">
<status-bar></status-bar>
</footer>
Resolve applies only for ng-views's controller, but header stuff needs to be translated as well, so I need to make a headerCtrl somehow wait before it tries to apply translations.
So I have made another unpopular decision to inform all controllers about the finished startup via a broadcast message and to wait until it is all done while showing the loading screen.
It looks fine and is pretty responsive (1sec per startup is acceptable at this point).
The problem is, that I see many design mistakes with this attempt and I just can not come up with the better design.
So my main question is:
How can I make it better? 1st service returns a whole array which is used by the 2nd service so I do not know how to combine it with promises?
I am afraid that with the development of the application I will find myself in a global variables and global events hell
Thanks in advance for your help!
It seems like you are looking for the angular-translate-loader-static-files extension for angular-translate. See the documentation here.
This together with proper configuration of $translateProvider will allow you to fetch json files with translations from the backend or even swap translations on demand - for example user changes language setting, controller reconfigures $translateProvider. Your job is done - everything will be fetched and updated automatically without a page reload.

Proper place for data-saving logic in AngularJS

App design question. I have a project which has a very large number of highly customized inputs. Each input is implemented as a directive (and Angular has made this an absolute joy to develop).
The inputs save their data upon blur, so there's no form to submit. That's been working great.
Each input has an attribute called "saveable" which drives another directive which is shared by all these input types. the Saveable directive uses a $resource to post data back to the API.
My question is, should this logic be in a directive at all? I initially put it there because I thought I would need the saving logic in multiple controllers, but it turns out they're really happening in the same one. Also, I read somewhere (lost the reference) that the directive is a bad place to put API logic.
Additionally, I need to introduce unit testing for this saving logic soon, and testing controllers seems much more straightforward than testing directives.
Thanks in advance; Angular's documentation may be… iffy… but the folks in the community are mega-rad.
[edit] a non-functional, simplified look at what I'm doing:
<input ng-model="question.value" some-input-type-directive saveable ng-blur="saveModel(question)">
.directive('saveable', ['savingService', function(savingService) {
return {
restrict: 'A',
link: function(scope) {
scope.saveModel = function(question) {
savingService.somethingOrOther.save(
{id: question.id, answer: question.value},
function(response, getResponseHeaders) {
// a bunch of post-processing
}
);
}
}
}
}])
No, I don't think the directive should be calling $http. I would create a service (using the factory in Angular) OR (preferably) a model. When it is in a model, I prefer to use the $resource service to define my model "classes". Then, I abstract the $http/REST code into a nice, active model.
The typical answer for this is that you should use a service for this purpose. Here's some general information about this: http://docs.angularjs.org/guide/dev_guide.services.understanding_services
Here is a plunk with code modeled after your own starting example:
Example code:
var app = angular.module('savingServiceDemo', []);
app.service('savingService', function() {
return {
somethingOrOther: {
save: function(obj, callback) {
console.log('Saved:');
console.dir(obj);
callback(obj, {});
}
}
};
});
app.directive('saveable', ['savingService', function(savingService) {
return {
restrict: 'A',
link: function(scope) {
scope.saveModel = function(question) {
savingService.somethingOrOther.save(
{
id: question.id,
answer: question.value
},
function(response, getResponseHeaders) {
// a bunch of post-processing
}
);
}
}
};
}]);
app.controller('questionController', ['$scope', function($scope) {
$scope.question = {
question: 'What kind of AngularJS object should you create to contain data access or network communication logic?',
id: 1,
value: ''
};
}]);
The relevant HTML markup:
<body ng-controller="questionController">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="saveModel(question)" />
</body>
An alternative using only factory and the existing ngResource service:
However, you could also utilize factory and ngResource in a way that would let you reuse some of the common "saving logic", while still giving you the ability to provide variation for distinct types of objects / data that you wish to save or query. And, this way still results in just a single instantiation of the saver for your specific object type.
Example using MongoLab collections
I've done something like this to make it easier to use MongoLab collections.
Here's a plunk.
The gist of the idea is this snippet:
var dbUrl = "https://api.mongolab.com/api/1/databases/YOURDB/collections";
var apiKey = "YOUR API KEY";
var collections = [
"user",
"question",
"like"
];
for(var i = 0; i < collections.length; i++) {
var collectionName = collections[i];
app.factory(collectionName, ['$resource', function($resource) {
var resourceConstructor = createResource($resource, dbUrl, collectionName, apiKey);
var svc = new resourceConstructor();
// modify behavior if you want to override defaults
return svc;
}]);
}
Notes:
dbUrl and apiKey would be, of course, specific to your own MongoLab info
The array in this case is a group of distinct collections that you want individual ngResource-derived instances of
There is a createResource function defined (which you can see in the plunk and in the code below) that actually handles creating a constructor with an ngResource prototype.
If you wanted, you could modify the svc instance to vary its behavior by collection type
When you blur the input field, this will invoke the dummy consoleLog function and just write some debug info to the console for illustration purposes.
This also prints the number of times the createResource function itself was called, as a way to demonstrate that, even though there are actually two controllers, questionController and questionController2 asking for the same injections, the factories get called only 3 times in total.
Note: updateSafe is a function I like to use with MongoLab that allows you to apply a partial update, basically a PATCH. Otherwise, if you only send a few properties, the entire document will get overwritten with ONLY those properties! No good!
Full code:
HTML:
<body>
<div ng-controller="questionController">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="save(question)" />
</div>
<div ng-controller="questionController2">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="save(question)" />
</div>
</body>
JavaScript:
(function() {
var app = angular.module('savingServiceDemo', ['ngResource']);
var numberOfTimesCreateResourceGetsInvokedShouldStopAt3 = 0;
function createResource(resourceService, resourcePath, resourceName, apiKey) {
numberOfTimesCreateResourceGetsInvokedShouldStopAt3++;
var resource = resourceService(resourcePath + '/' + resourceName + '/:id',
{
apiKey: apiKey
},
{
update:
{
method: 'PUT'
}
}
);
resource.prototype.consoleLog = function (val, cb) {
console.log("The numberOfTimesCreateResourceGetsInvokedShouldStopAt3 counter is at: " + numberOfTimesCreateResourceGetsInvokedShouldStopAt3);
console.log('Logging:');
console.log(val);
console.log('this =');
console.log(this);
if (cb) {
cb();
}
};
resource.prototype.update = function (cb) {
return resource.update({
id: this._id.$oid
},
angular.extend({}, this, {
_id: undefined
}), cb);
};
resource.prototype.updateSafe = function (patch, cb) {
resource.get({id:this._id.$oid}, function(obj) {
for(var prop in patch) {
obj[prop] = patch[prop];
}
obj.update(cb);
});
};
resource.prototype.destroy = function (cb) {
return resource.remove({
id: this._id.$oid
}, cb);
};
return resource;
}
var dbUrl = "https://api.mongolab.com/api/1/databases/YOURDB/collections";
var apiKey = "YOUR API KEY";
var collections = [
"user",
"question",
"like"
];
for(var i = 0; i < collections.length; i++) {
var collectionName = collections[i];
app.factory(collectionName, ['$resource', function($resource) {
var resourceConstructor = createResource($resource, dbUrl, collectionName, apiKey);
var svc = new resourceConstructor();
// modify behavior if you want to override defaults
return svc;
}]);
}
app.controller('questionController', ['$scope', 'user', 'question', 'like',
function($scope, user, question, like) {
$scope.question = {
question: 'What kind of AngularJS object should you create to contain data access or network communication logic?',
id: 1,
value: ''
};
$scope.save = function(obj) {
question.consoleLog(obj, function() {
console.log('And, I got called back');
});
};
}]);
app.controller('questionController2', ['$scope', 'user', 'question', 'like',
function($scope, user, question, like) {
$scope.question = {
question: 'What is the coolest JS framework of them all?',
id: 1,
value: ''
};
$scope.save = function(obj) {
question.consoleLog(obj, function() {
console.log('You better have said AngularJS');
});
};
}]);
})();
In general, things related to the UI belong in a directive, things related to the binding of input and output (either from the user or from the server) belong in a controller, and things related to the business/application logic belong in a service (of some variety). I've found this separation leads to very clean code for my part.

Can you bind data from one scope to update when another changes in angularJS

My web app depends on one specific variable changing throughout the user's visit. It controls what data the user will see at any given time, essentially akin to a TAG.
If the $scope.tagid = 1, is it possible to have another angular model to instantly update its own dataset when tagid is changed to $scop.tagid = 2?
<script >
function PageCtrl($scope) {
$scope.text = '<?=$tagid?>';
}
$scope.showThread = function(tagid) {
$http({method: 'GET', url: 'api/example/thread/id/' + tagid}).
success(function(data, status, headers, config) {
$scope.appDetail = data; //set view model
$scope.view = './Partials/detail.html'; //set to detail view
}).
error(function(data, status, headers, config) {
$scope.appDetail = data || "Request failed";
$scope.status = status;
$scope.view = './Partials/detail.html';
});
}
</script>
<div ng-controller="PageCtrl">
<input ng-model='text' />
<ul>
<li >
<span>{{text}}</span>
</li>
</ul>
</div>
Above is the skeleton of what i'm looking to do.
I realize that if I wanted to, I could call showThread() after each user action and update the data...however, because of the awy I'm looking to set up the site, It makes more sense to only change the tagid, then have everything else update immediately after, rather than picking and choosing each part of the site I want to update. i.e. there may, in addition to showThread(), be updateHeader(), changeSidebar() etc.
Thanks!
I have personally had success using a service; **Assuming that you are using 2 controllers on 1 page, I would create a service like this:
MyApp.app.service("tagDataSvc", function () {
var _tagId = {};
return {
getTagId: function () {
return _tagId;
},
setTagId: function (value) {
_tagId = value;
}
};
});
Next, inject this service into the controllers where this will be used.
In your main controller where you are controlling the TagId (PageCtrl), you would need to set the shared tagId value with a call to the service: tagDataSvc.setTagId($scope.text) You can do this explicitly, or add a $watch on $scope.text, or whatever you prefer.
Finally, in the second controller that you want to automagically update, add a $watch on this service's getTagId() function like so:
$scope.$watch(function () { return tagDataSvc.getTagId(); }, function (newValue, oldValue) {
if (newValue != null) {
$scope.tagId2 = newValue;
//reload whatever needs updating here
}
}, true);

Resources