updating time in angularjs app - javascript

In my angularjs app, i define a var for put a "prefix" in my all console.log
var app = angular.module('app', ['ngRoute', 'ngCookies', 'LocalStorageModule', 'ngResource', 'pascalprecht.translate']).run(function($rootScope, $timeout) {
$rootScope.defineCLC = "[ZR Console CL] " + updatingTime() + " ===> ";
[etc ...]
I use $rootScope.defineCLC in my controllers.
For having the time updated, i put in pure js, outside :
function updatingTime() {
setTimeout('updatingTime()', 3000);
var currentTime = new Date();
console.log('ok !');
return currentTime;
}
problem is it's doesnt't work, the time is always the date when app whas executed :/ how to update the time for having it good in the console.log ?

setTimeout('updatingTime()', 3000); will give you an error after 3secs (check the developer console in the browser) since you supply a string instead of a function.
You'll have to make a function and call it with angular's version of setInterval.
var app = angular.module('app', []).run(function($rootScope, $interval) {
var fun = function() {
$rootScope.defineCLC = "[ZR Console CL] " + new Date() + " ===> ";
};
$interval(fun, 3000);
}]);

Related

Angular Service Is Not A Function

I've created a simple logging service in Angular:
app.service('$userInteraction', [function() {
var userLog = "";
this.log = function (datetime, screen, logMessage) {
userLog.concat(datetime + "\t" + screen + " Screen\t" + logMessage + "\n");
}
this.getLog = function () {
return userLog;
}
this.clearLog = function () {
userLog = "";
}
}]);
And I use it in one of my controllers like so:
app.controller('myController', ['$scope', '$userInteraction', function($scope, $userInteraction) {
$userInteraction.log(Date(), 'Login', 'Some random message.');
}]);
But when I run my code I get the following error:
TypeError: $userInteraction.log is not a function
Though I could've sworn that it worked before. I'm fairly new to Angular so this might very well be a newbie mistake. Thanks in advance!
this question is old, but help someone... You code run on plunker, problably you have duplicate services name... Check all files angularjs and verify if exist another service with same name.
I had similar problem. Two services with same name and call did not have function called.

AngularJS returning undefined on first ng-click

Im a building a system that fetches new events based on the date sent to the API using AngularJS. I am currently still in in the learning stages of AngularJS so Im wondering is there something Im missing.
My problem is , even though the data loads correctly on the page load, when I click the button the first time I am getting undefined for $scope.newEvents even though it is successfully getting the data from the API (I can see in the console).
I was attempting to build a JSFiddle but I was having trouble getting the whole thing to work on it.
here is the html output...
The output...
<ul>
<li ng-repeat="event in events | orderBy:'-event_date' ">
<span >{{event.event_date}},{{event.event_name}}, {{event.event_venue}}, {{event.event_description}} </span>
</li>
</ul>
The get request in my js...
var eventApp = angular.module('eventApp', ['ngRoute']);
eventApp.factory("services", ['$http', function($http) {
var apiBase = 'http://example.net/angular-api/'
var service = {};
service.getEvents = function(latest_date){
return $http.get(apiBase + 'events?latest_date=' + latest_date);
}
return service;
}]);
When the page loads its working fine, it makes a successful request and updates $scope.events ...
var date = new Date();
$scope.todays_date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
$scope.events = [{}];
services.getEvents($scope.todays_date).then(function(data){
$scope.events = data.data;
});
But when click the button that loads the ng-click function I am getting undefined for my data. I initially figured there was something wrong with the date format, but the fact that it is successfully getting the data is what is confusing me. The problems start at then below...
$scope.addFiveNew = function (new_or_old) {
if (new_or_old == 'new') {
$scope.latest_date = $scope.getNewestDate();
services.getEvents($scope.latest_date).then(function(data){
$scope.newEvents = data.data;
});
console.log($scope.newEvents);
// update the list (this is currently failing on first click)
angular.forEach($scope.newEvents,function(item) {
$scope.events.push(item);
});
}
this function in the controller creates the date to send...
$scope.getNewestDate = function() {
var sortedArray = $filter('orderBy')($scope.events, 'event_date');
var NewestDate = sortedArray[sortedArray.length - 1].event_date;
return NewestDate;
};
Here is an example of some data...
{
"event_id":"1",
"event_name":"Event 1",
"event_date":"2014-09-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
}
The bit inside the then is asynchronous, so the rest of your code can run without the scope being updated by the return of your service method, right?
services.getEvents($scope.latest_date)
.then(function(data){ //whenever the service returns
$scope.newEvents = data.data; //update the scope
console.log($scope.newEvents); //log the results
// update the list
angular.forEach($scope.newEvents,function(item) {
$scope.events.push(item);
});
});
It looks to me like the getEvents call on your service is returning a promise. Calling .then on a promise will call the passed function asynchronously. So, your $scope.newEvents = data.data; will get called after the rest of the statements in that block. I think you can change your .then statement to the following and it should work:
$scope.addFiveNew = function (new_or_old) {
if (new_or_old == 'new') {
$scope.latest_date = $scope.getNewestDate();
services.getEvents($scope.latest_date).then(function(data){
$scope.newEvents = data.data;
console.log($scope.newEvents);
// update the list (this is currently failing on first click)
angular.forEach($scope.newEvents,function(item) {
$scope.events.push(item);
});
});
}
}

angular js treeview getting slower and slower

I am trying to make a treeview control in angular js.
I have used the angular js directive( referred this link : angularjs treeview)
I have modified the above for having a big tree that contain tags.
My fiddle : fiddle sample
//angular module
var myApp = angular.module('myApp', ['angularTreeview']);
//test controller
myApp.controller('myController', function($scope){
$scope.clean_tree = function()
{
$scope.roleList = [];
};
$scope.show_tree = function () {
//debugger;
console.log("tag start : " + new Date());
//$scope.tagList = eval(abc);
$scope.roleList = $scope.roleList_tag;
$scope.$apply();
console.log("tag end : " + new Date());
};
The problem
The rendering of the tree gets slower and slower if I continuously follow this pattern:
click on : Tree Structure
click on : clean
Go To 1.
I dont understand why this is becoming slower and slower when i follow this pattern

Adding a Second Service to an Angular Module

Does anyone know if you can add a second service to an angular module?
It seems when I try, I end up breaking angular.
This Works:
var MyModule = angular.module('MyModule',[]);
MyModule.service('MyService',function(){
this.message = 'checking in';
});
MyModule.controller('MyController', function($scope,MyService){
console.log(MyService.message);
});
// output
// checking in
This DOES work: I had an issue elsewhere in my code. I'm leaving this up because it is still hard to find angular documentation with two services being applied (which I promise I looked for)
var MyModule = angular.module('MyModule',[]);
MyModule.service('MyService',function(){
this.message = 'checking in';
});
MyModule.service('MyServiceTwo',function(){
this.message = 'checking in';
});
MyModule.controller('MyController', function($scope,MyService,MyServiceTwo){
console.log(MyService.message);
});
// no output
In your second service definition just retrieve the module - don't redefine it:
var MyModule = angular.module('MyModule');

jasmine, $q is undefined

I'm going through some of the examples online for AngularJS to try to understand how it works. I'm trying to use jasmine to test like in the examples. In my spec file, I have:
var Person = function (name, $log) {
this.eat = function (food) {
$log.info(name + " is eating delicious " + food);
};
this.beHungry = function (reason) {
$log.warn(name + " hungry " + reason);
};
};
var bob = new Person();
describe("describe", function () {
it("$q", function () {
var pizzaOrderFulfillment = $q.defer();
var pizzaDelivered = pizzaOrderFulfillment.promise;
pizzaDelivered.then(bob.eat, bob.beHungry);
pizzaOrderFulfillment.resolve("resolved");
$rootScope.$digest();
expect($log.TypeInfo.logs).toContain(["resolved"]);
});
});
I get
ReferenceError: $q is not defined
Am I using Jasmine correctly? I basically am just writing all my angular and jasmine code in the spec.js file. When I had the angular code in another file, my spec.js file couldn't find it. Probably because I didn't set any dependencies up on what gets loaded first since I'm just starting out with this stuff.
Edit, fixed the $ to be $q and the referencerror.
I guess you are not injecting the $q service in your unit test.
For example in your beforeEach block you can inject it:
var q;
beforeEach(inject(function($q) {
q = $q;
}));
And then in your unit test:
describe("describe", function () {
it("$q", function () {
var pizzaOrderFulfillment = q.defer();
var pizzaDelivered = pizzaOrderFulfillment.promise;
pizzaDelivered.then(bob.eat, bob.beHungry);
pizzaOrderFulfillment.resolve("resolved");
$rootScope.$digest();
expect($log.TypeInfo.logs).toContain(["resolved"]);
});
});

Categories

Resources