AngularJS : Asynchronously initialize filter - javascript

I'm having trouble trying to initialize a filter with asynchronous data.
The filter is very simple, it needs to translate paths to name, but to do so it needs a correspondance array, which I need to fetch from the server.
I could do things in the filter definition, before returning the function, but the asynchronous aspect prevents that
angular.module('angularApp').
filter('pathToName', function(Service){
// Do some things here
return function(input){
return input+'!'
}
}
Using a promise may be viable but I don't have any clear understanding on how angular loads filters.
This post explains how to achieve such magic with services, but is it possible to do the same for filters?
And if anyone has a better idea on how to translate those paths, I'm all ears.
EDIT:
I tried with the promise approch, but something isn't right, and I fail to see what:
angular.module('angularApp').filter('pathToName', function($q, Service){
var deferred = $q.defer();
var promise = deferred.promise;
Service.getCorresp().then(function(success){
deferred.resolve(success.data);
}, function(error){
deferred.reject();
});
return function(input){
return promise.then(
function(corresp){
if(corresp.hasOwnProperty(input))
return corresp[input];
else
return input;
}
)
};
});
I'm not really familliar with promises, is it the right way to use them?

Here is an example:
app.filter("testf", function($timeout) {
var data = null, // DATA RECEIVED ASYNCHRONOUSLY AND CACHED HERE
serviceInvoked = false;
function realFilter(value) { // REAL FILTER LOGIC
return ...;
}
return function(value) { // FILTER WRAPPER TO COPE WITH ASYNCHRONICITY
if( data === null ) {
if( !serviceInvoked ) {
serviceInvoked = true;
// CALL THE SERVICE THAT FETCHES THE DATA HERE
callService.then(function(result) {
data = result;
});
}
return "-"; // PLACEHOLDER WHILE LOADING, COULD BE EMPTY
}
else return realFilter(value);
}
});
This fiddle is a demonstration using timeouts instead of services.
EDIT: As per the comment of sgimeno, extra care must be taken for not calling the service more than once. See the serviceInvoked changes in the code above and the fiddles. See also forked fiddle with Angular 1.2.1 and a button to change the value and trigger digest cycles: forked fiddle
EDIT 2: As per the comment of Miha Eržen, this solution does no logner work for Angular 1.3. The solution is almost trivial though, using the $stateful filter flag, documented here under "Stateful filters", and the necessary forked fiddle.
Do note that this solution would hurt performance, as the filter is called each digest cycle. The performance degradation could be negligible or not, depending on the specific case.

Let's start with understanding why the original code doesn't work. I've simplified the original question a bit to make it more clear:
angular.module('angularApp').filter('pathToName', function(Service) {
return function(input) {
return Service.getCorresp().then(function(response) {
return response;
});
});
}
Basically, the filter calls an async function that returns the promise, then returns its value. A filter in angular expects you to return a value that can be easily printed, e.g string or number. However, in this case, even though it seems like we're returning the response of getCorresp, we are actually returning a new promise - The return value of any then() or catch() function is a promise.
Angular is trying to convert a promise object to a string via casting, getting nothing sensible in return and displays an empty string.
So what we need to do is, return a temporary string value and change it asynchroniously, like so:
JSFiddle
HTML:
<div ng-app="app" ng-controller="TestCtrl">
<div>{{'WelcomeTo' | translate}}</div>
<div>{{'GoodBye' | translate}}</div>
</div>
Javascript:
app.filter("translate", function($timeout, translationService) {
var isWaiting = false;
var translations = null;
function myFilter(input) {
var translationValue = "Loading...";
if(translations)
{
translationValue = translations[input];
} else {
if(isWaiting === false) {
isWaiting = true;
translationService.getTranslation(input).then(function(translationData) {
console.log("GetTranslation done");
translations = translationData;
isWaiting = false;
});
}
}
return translationValue;
};
return myFilter;
});
Everytime Angular tries to execute the filter, it would check if the translations were fetched already and if they weren't, it would return the "Loading..." value. We also use the isWaiting value to prevent calling the service more than once.
The example above works fine for Angular 1.2, however, among the changes in Angular 1.3, there is a performance improvement that changes the behavior of filters. Previously the filter function was called every digest cycle. Since 1.3, however, it only calls the filter if the value was changed, in our last sample, it would never call the filter again - 'WelcomeTo' would never change.
Luckily the fix is very simple, you'd just need to add to the filter the following:
JSFiddle
myFilter.$stateful = true;
Finally, while dealing with this issue, I had another problem - I needed to use a filter to get async values that could change - Specifically, I needed to fetch translations for a single language, but once the user changed the language, I needed to fetch a new language set. Doing that, proved a bit more tricky, though the concept is the same. This is that code:
JSFiddle
var app = angular.module("app",[]);
debugger;
app.controller("TestCtrl", function($scope, translationService) {
$scope.changeLanguage = function() {
translationService.currentLanguage = "ru";
}
});
app.service("translationService", function($timeout) {
var self = this;
var translations = {"en": {"WelcomeTo": "Welcome!!", "GoodBye": "BYE"},
"ru": {"WelcomeTo": "POZHALUSTA!!", "GoodBye": "DOSVIDANYA"} };
this.currentLanguage = "en";
this.getTranslation = function(placeholder) {
return $timeout(function() {
return translations[self.currentLanguage][placeholder];
}, 2000);
}
})
app.filter("translate", function($timeout, translationService) {
// Sample object: {"en": {"WelcomeTo": {translation: "Welcome!!", processing: false } } }
var translated = {};
var isWaiting = false;
myFilter.$stateful = true;
function myFilter(input) {
if(!translated[translationService.currentLanguage]) {
translated[translationService.currentLanguage] = {}
}
var currentLanguageData = translated[translationService.currentLanguage];
if(!currentLanguageData[input]) {
currentLanguageData[input] = { translation: "", processing: false };
}
var translationData = currentLanguageData[input];
if(!translationData.translation && translationData.processing === false)
{
translationData.processing = true;
translationService.getTranslation(input).then(function(translation) {
console.log("GetTranslation done");
translationData.translation = translation;
translationData.processing = false;
});
}
var translation = translationData.translation;
console.log("Translation for language: '" + translationService.currentLanguage + "'. translation = " + translation);
return translation;
};
return myFilter;
});

Related

How to show a loading message before filter with AngularJS?

I need to show some "Loading Message" when a filter is about to happen with AngularJS. My filter is fast, so I can't just show it before return the filtered data. My code:
.filter('filterName', function () {
return function (pacotes, escopo) {
var filtered = [];
pacotes.forEach(function (pacote) {
if (condition)
filtered.push(pacote);
});
return filtered;
}
})
What can I do to show some message, div, anything, before return this data?
Somewhere in your html:
<p id="loadingMessage" ng-show="showMessage"></p>
Filter:
.filter('filterName', function () {
$scope.showMessage = true;
$timeout(return function (pacotes, escopo) {
var filtered = [];
pacotes.forEach(function (pacote) {
if (condition)
filtered.push(pacote);
});
$scope.showMessage = false;
return filtered;
}, 3000);
})
I was not able to test this since I don't have all of your code. But something like this should work assuming I have the syntax right. You would have to inject $scope and $timeout in the appropriate places for this to work though.
Edit: I just realized escopo likely means scope in another language. Assuming that is true and you are actually passing in the scope, just put escopo where I have $scope.

AngularJS: triggering the evaluation of bindings that include a filter

I am working on a project in which the client needs to be able to change each and any string that we've used in the application. This need is similar to i18n needs, except that what we, the dev team, provided and the set of strings that the client may end up with after their modifications are both in the same language.
I have therefore implemented a filter, so that strings in html views are written as an Angular expression such as {{'one.code.on.view1' | label }}. The filter relies on a service that "holds the entire set of labels in memory", so to speak.
I've designed a simple UI for users to modify text labels: all labels are shown in an angular-ui-grid. Each line has the (non-modifiable) code and the (modifiable) label. Using the grid's inline edit feature, I save the modified label to the database. So far, so good.
My problem is that when saving the modified label to the database, I also update the entry of that label in the service that "holds labels" but unfortunately, in case the modified label were displayed on screen, the old value isn't updated.
My question is: how can I trigger an evaluation of bindings on the view? I have used every $timeout or $apply trick I knew but to no avail, which isn't very surprising since all the code runs within Angular contexts.
Here is the code of the filter and service: (for the sake of clarity, "libellé" is the French word for "label" even though we sometimes improperly use "label"; and 'scoop' is the name of the project, hence its use as a prefix)
function scoopLabelSceFn($resource, $rootScope, $timeout) {
var rest = $resource('admin/libelle/list', {}, {});
var labels = [];
function loadAllLabels() {
labels = rest.query({}, function(result) {
var liste = [];
for (var idx = 0; idx < result.length; ++idx) {
var entry = result[idx];
liste[entry.code] = entry.libelle;
}
labels = liste;
});
}
loadAllLabels();
return {
getLabels : function() {
return labels;
},
reloadLabels : function() {
loadAllLabels();
},
updateLabel : function(code, newValue) {
labels[code] = newValue;
}
};
}
function scoopLabelFilterFn($log, scoopLabelService) {
return function(input) {
if (angular.isString(input)) {
var libelles = scoopLabelService.getLabels();
var res = libelles[input];
if (res) {
return res;
}
$log.log("scoopLabelFilter: no entry for: " + input);
return input;
}
$log.log("scoopLabelFilter: incorrect parameter type");
return "";
};
}
module.filter("label", [ "$log", "scoopLabelService", scoopLabelFilterFn ]);
module.factory("scoopLabelService", [ "$resource", "$rootScope", "$timeout", scoopLabelSceFn ]);
Actually, there is nothing conceptually wrong with the code.
The way Angular treats filters has apparently changed somewhere on the 1.3.x branch. As a consequence, the code returning the filter function has to be modified.
Old code:
return function(input) {
...
Modified code:
function filterFn(input) {
...
filterFn.$stateful = true;
return filterFn;
With this, all expressions related to the filter are automatically reevaluated.

angularFire 3 way data binding won't update an function

I have a firebaseObject (MyFirebaseService.getCurrentUser()) bind to $scope.user.
After binding successful, I loop tho the object to see if the object contain "associatedCourseId" equal to some value ($stateParams.id). If does, the $scope.finishLessonCount count up. The problem is, when I add new Object inside the firebaseObject (that bindto user) via other page OR inside firebase, the finishLessonCount value won't change as what I expect for 3 way binding. I need to refresh the page to see the finishLessonCount reflect the true value. What is wrong? I want the finishLessonCount change using the compare function as I add more finishedLessons into the firebaseObject. Please see code below:
MyFirebaseService.getCurrentUser().$bindTo($scope, "user").then(function(){
for (var key in $scope.user.finishedLessons) {
if ($scope.user.finishedLessons.hasOwnProperty(key)) {
if ($scope.user.finishedLessons[key].associatedCourseId == $stateParams.id) {
$scope.finishLessonCount++;
}
}
};
console.log ($scope.finishLessonCount);
});
UPDATE 1 according to #Kato solution:
I decide to use Extending firebaseOject way to solute this problem. But still, it does not. I did not use factory here to simplify thing since I need to pass in courseId to do the operation. Here is my code:
function countLessons(lessons, courseId) {
var count = 0;
for(var key in lessons) {
if( lessons[key].associatedCourseId == courseId) {
count++;
}
}
return count;
}
var UserWithLessonsCounter = $firebaseObject.$extend({
$$updated: function(snap) {
var changed = $firebaseObject.prototype.$$updated.call(this, snap);
this.lessonCount = countLessons(this.finishedLessons, $stateParams.id);
}
});
var refTemp = new Firebase($rootScope.baseUrl + "users/" + $rootScope.userId);
var userTemp = new UserWithLessonsCounter(refTemp);
userTemp.$bindTo($scope, "userTemp").then(function(){
console.log($scope.userTemp);
});
userTemp.$watch(function() {
console.log("Does this run at all? " + $scope.userTemp.lessonCount);
});
I update the user object, the lessonCount value did not change unless I refresh the page. And the console.log inside $watch did not run at all. What is wrong?
The promise returned by $bindTo is called exactly once. It's not an event listener. You can't listen to this to get updated each time there is a change.
Please read the guide, start to finish, and read about Angular's $watch method before continuing down this route, as with some fundamental knowledge, this should not have been your first instinct.
A beginner approach would be to utilize $watch:
MyFirebaseService.getCurrentUser().$bindTo($scope, "user");
$scope.$watch('user', function() {
for (var key in $scope.user.finishedLessons) {
if ($scope.user.finishedLessons.hasOwnProperty(key)) {
if ($scope.user.finishedLessons[key].associatedCourseId == $stateParams.id) {
$scope.finishLessonCount++;
}
}
};
console.log ($scope.finishLessonCount);
});
Or, having familiarized with the AngularFire API, one might pick $scope.user.$watch() in place of the scope method, which would prove more efficient.
Having written a large portion of the AngularFire code, I would pick the $extend tool, which was added precisely for use cases like this:
// making some assumptions here since you haven't included
// the code for your firebase service, which does not seem SOLID
app.factory('UserWithLessonsCounter', function($firebaseObject) {
return $firebaseObject.$extend({
$$updated: function(snap) {
var changed = $firebaseObject.prototype.$$updated.call(this, snap);
this.lessonCount = countLessons(this.finishedLessons);
return changed;
}
});
});
function countLessons(lessons) {
var count = 0;
for(var key in lessons) {
if( lessons.hasOwnProperty(key) ) {
count++;
}
}
return count;
}
And now in your controller:
app.controller('...', function($scope, UserWithLessonsCounter) {
var ref = new Firebase(...);
var user = new UserWithLessonCounter(ref);
user.$bindTo($scope, 'user');
user.$watch(function() {
console.log($scope.user.lessonCount);
});
});

Factory has two methods, one is $http method with $promise - how to reference the other method from within the first one's success function?

In one of my factories I need to set a variable when data is fetched (through $http) so I can access it in my controller (the intention is to display a spinner image until the data is loaded).
.factory('LoadData', function LoadData($http, $q){
return {
getMyData: function(){
return $http(
// implementation of the call
).then(
function(response){
var myData = response.data;
// this should be reference to the other method (getLoadStatus)
// where I want to change its value to "true"
// this doesn't work - "this" or "self" don't work either because we're in another function
LoadData.getLoadStatus.status = true;
}
);
},
// by calling the below method from my controller,
// I want to mark the completion of data fetching
getLoadStatus = function(){
var status = null;
return status;
}
}
}
I hope you got the idea - how could this be accomplished? Also, I'm open to any suggestions which are aimed towards a better approach (I want to pick up best practice whenever possible).
Status is essentially a private variable; use it as:
.factory('LoadData', function LoadData($http, $q){
var status = null; // ESSENTIALLY PRIVATE TO THE SERVICE
return {
getMyData: function(){
return $http(...).then(function(response){
...
status = true;
});
},
getLoadStatus = function(){
return status;
}
};
})
There are several ways.
Here's one which I prefer to use:
.factory('LoadData', function LoadData($http, $q){
var status = false;
var service = {
getMyData: getMyData,
status: status
};
return service;
function getMyData() {
return $http(
// implementation of the call
).then(
function(response){
var myData = response.data;
status = true;
}
);
}
}
This provides good encapsulation of your methods and gives you a clean interface to export. No need for the getter method if you don't want it.
Inspiration via John Papa's Angular style guide (found here).
You could simply store variable flag in closure:
.factory('LoadData', function LoadData($http, $q) {
var status = false;
return {
getMyData: function() {
status = false;
return $http(/* implementation of the call */).then(function(response) {
status = true;
return response.data;
});
},
getLoadStatus: function() {
return status;
}
}
});
Also if getMyData loads fresh data every time, it's important to reset status to false before each request.
I actually decide to use a promise in my controller after calling this service and when data is returned, I am simply making the status true. It seems that is best practice to have a promise returned when calling a service so I should be good.

Getting a Filter to handle a Promised Service

I have already started to rework this code to operate synchronously, but out of curiosity and a desire to support both means, I need some help understanding how to get a filter to jive with a promise. As some other posts mention a filter seems to just resolve to {} from a promise.
Basic Pattern
Here's a breakdown:
Define a service in the module that returns a promise instead of an object
module.factory('promisedSvc', ['$http', function($http) {
var httpPromise = null,
servicePromise = null,
service = {},
dataSet = {};
var httpPromise = $http.get('somedata.json').success(function(data) {
dataSet = data;
});
servicePromise = httpPromise.then(function(){
service.getData = function(key) {
return dataSet[key];
};
service.addData = function(key, value) {
dataSet[key] = value;
};
return service;
});
/*
In actuality I proxied the service methods onto the promise because
I didn't want consumers of the service to have to deal with it being
a promise. There is the caveat of setting properties on a class I
don't own (property collisions), a risk I'm okay taking, but YMMV
Commented out proxies
servicePromise.getData = function(key) {
return this.then(function(svc){
return svc.getData(key);
});
};
servicePromise.addData = function(key, value) {
this.then(function(svc){
svc.addData(key, value);
});
};
*/
return servicePromise;
}]);
Controllers can handle this promisedSvc fine, you just get the promise injected into the controller and then use the then function on the promise to wrap the setting of a $scope property to the function call on the eventual service object: getData(key) or setData(key, value). Alternately you can just treat it as normal if you proxied the functions onto the promise like in the commented out block.
Filters do not seem to inherently handle promises like $scope does. I am looking for a way to get the filter to inject the promisedSvc and be able to call getData(key) without it resolving to {} because the promise has not resolved yet. Below is an example of what does not work:
module.filter('svcData', ['promisedSvc', function(promisedSvc) {
return function(input) {
return promisedSvc.then(function(svc) {
var value = svc.getData(input);
return value;
});
};
}]);
So is there a way to write the filter to be able to resolve the value?
Use Case
That is the simplified pattern of what I am trying to achieve. For those curious, my actual use case is to pre-fetch i18n/l10n resource bundle information so I can localize all the text in my application. The pre-fetch could all be in the Javascript environment (attached to some already loaded global or in a provider), but we also have scenarios with database-stored Resource Bundles so I needed a version of code that can pre-fetch all the information from the server via AJAX.
It's not exactly what I'm looking for, but at least to document a workaround:
It's possible to use a function on the $scope instead of a filter.
module.factory('promisedSvc', ['$http', '$rootScope', function($http, $rootScope) {
var httpPromise = null,
servicePromise = null,
service = {},
dataSet = {};
var httpPromise = $http.get('somedata.json').success(function(data) {
dataSet = data;
});
servicePromise = httpPromise.then(function(){
service.getData = function(key) {
return dataSet[key];
};
service.addData = function(key, value) {
dataSet[key] = value;
};
//Here is the addition to setup the function on the rootScope
$rootScope.svcData = function(key) {
return service.getData(key);
};
return service;
});
return servicePromise;
}]);
And then in a template instead of {{ 'key1' | svcData }} you would use {{ svcData('key1') }}
I tested that if you delay the promises resolution (for example setup a wait in the $http.success) that the impact is the page loads, but the values from the svcData function will only populate into the template once the promises resolve.
Still would be nice to accomplish the same with a filter if possible.

Categories