I make a simple demo in my Pc which is working fine .But when I make fiddle to ask Question say
Uncaught Error: [$injector:nomod] Module 'myapp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
can you please tell why it is occur ? I am getting data n my pc.Actually my real Question how to refresh or call same webservice after some tome mean after 1 minutes.As in jquery we have setinterval function .how I will achieve in this angular ?
here is fiddle
http://jsfiddle.net/acboLcv2/1/
var app=angular.module("myapp");
app.factory('test', function($http) {
//This whole object is returned when the Service runs. It is a singleton
//and its properties can be accessed from any controller
return {
stationDashBoard: function(callback,error) {
$http.get('http://184.106.159.143:8180/FGRailApps/jservices/rest/a/departure?crsCode=VIC').success(callback).error(error);
}
}
});
function departureContrl($scope,test){
$scope.loading=true;
test.stationDashBoard(function(data){
console.log(data);
$scope.data=data.data;
$scope.loading=false;
//alert(data);
},function(error){
alert('error')
}) ;
}
Thanks
So there's a few things with your site you need to focus on:
Getting rid of the module error:
I think it's fixed, but heuristically I suggest:
Ensure that the declaration of an angular module includes the empty array as as already been mentioned. This is necessary, thusly:
angular.module("test", []);
Ensure you reference the angular app in the html. I suggest body for most applications:
CORS error
You're trying to load data from a different domain with $http.get(...). This won't work unless you do some kind of CORS hackery or you get the data from the same domain. Ie, you'd have to host this code on http://184.106.159.143:8180 (in this example).
Polling request
You're asking about fetching data from a server every n seconds. This is quite easy and the method you suggest with setTimeout() would work but would need to be integrated into the angular Digest Loop:
I suggest using $timeout because it will work with angular's rendering something like this (this is pseudocode, not tested):
var fetchFromServer(cb){
$timeout(function(){
$http.get(...).then(function(data){
//Do something with the retrieved data
cb(fetchFromServer); //Recurse
});
}, 15000);
};
fetchFromServer(fetchFromServer);
Otherwise you can use setTimeout as you normally would in javascript, but don't forget to call the $scope.$apply() method to render things in angular if you do it outside the digest loop or else it will appear as if there has been no effect.
Related
I have a few controllers that call the method getData() from a service.
In order to not do extra http calls for the same json file, i'm using something like this:
QuizApp.service('quizService', ['$http', function($http) {
var quizService = {},
quizData;
quizService.getData = function() {
return quizData ? quizData : quizData = $http.get('quiz.json');
};
return quizService;
}]);
...but things don't work properly if I do it like that (the data is used to populate a slider and a thumbnail gallery with angular-slick and some problems arise. For now it maybe doesn't matter, I just want to know if the code above makes sense).
On the other hand, if I write getData() like this:
QuizApp.service('quizService', ['$http', function($http) {
var quizService = {},
quizData;
quizService.getData = function() {
quizData = $http.get('quiz.json');
return quizData;
};
return quizService;
}]);
... which will do various http requests for the same json file (doesn't look like a good practice to me), everything works fine and the slick angular gallery works properly. But not 100% of the times though: kind of randomly things don't work well too (same symptoms. I might describe them but again, I don't think that's the point here)
So, in general, regardless of the context, which one of those versions of getData() looks good and which doesn't and why?
UPDATE
As Mark pointed out, Angular has a built in cache, but it's set to false by default. Here is a post and here is the documentation.
If I cache the result of the http request though I get the same problem (I'm not describing it here) I was getting with my second option, and it has apparently nothing to do with that.
Actually, it seems that if I repeat the http request two times (as in my second snippet of code) things work by chance (90% of the time?).
So, by caching the result, at least I get a consistent result, which means in this case that the slick-angular thing won't work properly (never) and I have to look for a solution somewhere else.
Angular $http has a built in cache, which you could make use of here. You can cache all $http requests, which is probably a bad idea, or specific ones.
On a very simple level, this should work for you
quizService.getData = function() {
return $http.get('quiz.json', {cache: true}).then(quizData => {
return quizData;
});
};
You can find out more in the Angular docs for $http
I have an iframe with ASP.NET application, that contains UpdatePanel. I started using Angular inside the application, but things didn't work because of the .NET postbacks.
To solve this, I used this solution:
with (Sys.WebForms.PageRequestManager.getInstance()) {
add_endRequest(onEndRequest); // regester to the end Request
}
function onEndRequest(sender, args) {
angular.bootstrap($('#mainDiv'), ['defaultApp']);
var rootscope = angular.element('#mainDiv').scope();
if (rootscope) {
rootscope.$apply();
}
}
And it works great.
The problem is that when I dynamically load a different user control in the ASP.NET page, with another ng-controller, Angular throws an error saying the app is already loaded:
App Already Bootstrapped with this Element
So the question is: How can I check if the app is already bootstrapped? Can I reload this module? Can I remove it from the element and than bootstrap it again?
Thanks.
It's not good practice to access scope from outside the app, so it's not enabled in well-built production applications. If you need to access/apply scope then there's something strange/unsupported about your use case.
However, the right way to check whether an element has been bootstrapped is the way the Angular library does it which is to load up the element and check for an injector. So you'd want angular.element(document.querySelector('#mainDiv')).injector(); which makes your code:
function onEndRequest(sender, args) {
var element = angular.element(document.querySelector('#mainDiv'));
//This will be truthy if initialized and falsey otherwise.
var isInitialized = element.injector();
if (!isInitialized) {
angular.bootstrap(element, ['defaultApp']);
}
// Can't get at scope, and you shouldn't be doing so anyway
}
Can you tell us why you need to apply the scope?
You could simply check for the scope of mainDiv, if angular.element(document.querySelector('#mainDiv')).scope() is not undefined then that means angular has been not initialized yet.
You code will be like below.
CODE
function onEndRequest(sender, args) {
//below flag will be undefined if app has not bootsrap by angular.
var doesAppInitialized = angular.element(document.querySelector('#mainDiv')).scope();
if (angular.isUndefined(doesAppInitialized)) //if it is not
angular.bootstrap($('#mainDiv'), ['defaultApp']);
var rootscope = angular.element('#mainDiv').scope();
if (rootscope) {
rootscope.$apply(); //I don't know why you are applying a scope.this may cause an issue
}
}
Update
After angular 1.3+ release in later Aug 2015, there it added performance related improvement by disabling debugging information by disabling debug info. So normally we should enable debuginfo option to false to have good performance improvement on Production environment. I don't wanted to write too much about it as its already covered by #AdamMcCormick answer, which is really cool.
I don't know what it is about JS, but I have a mental block. I apologize for the dumb question, but I'm at a loss because no matter how much I read I cannot get the academics into practice. Especially when it comes to nested functions.
I have a controller, lets say FileCtrl. Inside of it I have the the following that listens for file added to an input field via a directive. I'm attempting to inject an Angular JS factory service service called fileReader (a queue service for HTML5 FileReader).
However,I keep getting a undefined error on fileReader. I know why because, it cannot see fileReader, but injecting it at $scope.$on and then again on $scope.$apply doesn't work. Also, adding fileReader as a closure at the end of $scope.$on doesn't work either.
I should add that I can see the args.file and if I remove the fileReader code it will push the file no problem, but I then have no thumbnail. So I it works, just not with the fileReader and that is because Im doing something wrong with injection.
Side note, to Vals comment below I use apply as I found there was a image render sync issue without it which works fine for smaller images, but with larger images it freezes which is why I'm attempting to create and use a $q fileReader service. I suppose another way to solve for it would be to create a watch / directive on the array entry and when img comes back with the 64 encode string populate the html element ... like I said JS mental block :)
myApp.controller('FileController', ['$scope', 'FileReaderService', function($scope, FileReaderService ){
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
$scope.progress = 0;
fileReader.readAsDataUrl(args.file, $scope)
.then(function(result) {
$scope.imageSrc = result;
});
$scope.files.push(args.file);
});
});
});
In AngularJS not all functions are been processed by Dependency Injection. In Controllers, Directives (in definition of directive and in controller, not on link or compile), Servicies AngularJS inject requested instances, but in some other functions (like event listeners) arguments are passed by position.
In your case you need to put fileReader into definition on controller, not on event listener.
Also you need to remove apply because event listeners added via $on are included into digest loop.
Thanks to all for your replies. Val you made me go back and do a little more research and I found the answer with a little debugging. Not sure I understand why yet, but I have an idea.
If there is an error in your factory service, in my case, FileReaderService angular won't always explode when bootstrapping the service, will only explode when you call the service, which makes kind of makes sense. If something is wrong in the service the entire service will not boot. Also, you won't get any error message when injecting it into the controller. I had to place a watch on the module and noticed there was a reference error. I found I had a missing function.
Purely inexperience on my end, but I kept trying to capture the results form the $q service, which is was doing fine, but then attempting to inject to outside the $q return i.e. I was attempting to capture $scope.imageSrc = result and insert it post the .then, which doesn't work as you have a sync issue. I could see the value in the $scope.files, but it would not console.log or show up in HTML. So I moved all the file manipulation into the .then and it works perfectly. Logical when you think about it :) why have a $q if you not going to use it ... lol.
// problem code
fileReader.readAsDataUrl(args.file, $scope)
.then(function(result) {
$scope.imageSrc = result;
});
// cannot and should not try to work the results outside the return promise
$scope.files.imgSource = $scope.imageSrc;
$scope.files.push(args.file);
//Fixed and working code
myApp.controller('FileController', ['$scope', 'FileReaderService', function($scope, FileReaderService ){
var reader;
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.progress = 0;
var file = args.file;
FileReaderService.readAsDataUrl(file, $scope)
.then(function(result) {
file.imgSource = result;
$scope.files.push(file);
});
});
});
I have a directive that reads sync data from <title> tag. Then it trigger a service which $broadcast the data to all controllers.
But the controllers under <body> tag are not receiving this. However if I move ng-app attr from html to body, and move the directive with the controller from head to body. Then all the controllers will work properly.
Here is my sample code: http://jsbin.com/oBAMOs/4/edit?html,js,console,output
From the code I believe you can pretty much guess what I am trying to do. So why is this happening and is there a better way to achieve this?
navCtrl doesn't exist at the point at which you send your broadcast. You can confirm that by putting log statements at the beginning of each controller and the send. You'll see you send before navctrl is created. ("title" happens then "send" then "nav")
An easy way to resolve this is to push your $broadcast till after the browser finishes all current queued up tasks (which will include rendering the rest of the DOM, and thus the instantiation of navCtrl). You can accomplish this by placing the broadcast within a $timeout that has a delay of 0. As follows:
$timeout (function() {
$rootScope.$broadcast('processed');
},0);
and make sure to pass timeout in:
.factory('syncPageid', ['$rootScope','$timeout', function($rootScope,$timeout){
This is a by product of the single threaded nature of javascript. For a discussion on why timeout works here and the underlying issue you can check out: setTimeout with zero delay used often in web pages, why? and http://ejohn.org/blog/how-javascript-timers-work/
Instead of just
$rootScope.$broadcast('processed');
you can have
$rootScope.$broadcast('processed', "data_you_need_to_pass_around");
and catch that like
$scope.$on('processed', function (e, args){
$scope.title = args;
console.log('titleCtrl: ' + args);
});
http://jsbin.com/oBAMOs/11/edit
And then ofcourse your syncPageid factory can expose it to all other code bits that is interested in pageid. But having a factory just to facilitate passing data between places bits makes no good sense.
I am creating a leader board and need to rotate views that contain data that the team wants to see. I am using WebAPI with Durandal.
I have a collection of strings that contain the name of each of the modules. This lives in Durandals app.js (called moduleList)
define(['./system', './viewEngine', './composition', './widget', './modalDialog', './events'],
function(system, viewEngine, composition, widget, modalDialog, Events) {
var app = {
title: 'Application',
moduleList: [
"petsSoldToday",
"conversionRatioToday"
]
.
.
.
};
Events.includeIn(app);
return app;
});
What I would like to do is call router.activate([moduleName]) on a loop so that all the modules will be displayed, one by one.
I have tried creating something simple in the shell.js activate function that basically calls
setTimeout(router.activate(current), 10000);
current being the next module in the list. However, this causes a javascript error
Uncaught SyntaxError: Unexpected identifier
I don't see anything in the stack that shows why either. Honestly, I don't know what else to try.
How can this be done? Can it be done at all?
The code in your setTimeout function is executed immediately and that value is then passed to the setTimeout method (given you an error, because activate does not return a function).
You should put it inside a closure:
setTimeout(function(){
router.activate(current)
}, 10000);