I am working on a single page app using angularjs. The app has many navigator pages that run ajax calls.
The problem is that whenever the app launches all ajax code is run for all pages (although pages have not been navigated to yet)
I need a way to run the below only when the navigator page is requested. How can I do that without placing my code in a function and calling the function?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
Related
I have the following code for AngularJS. Within is a checkStatus function that invokes a web api to check a status of a user's PC. The problem I'm having is that the checkStatus() function is firing twice and hitting the back-end service twice. I do not understand why.
<script>
(function() {
var pageApp = angular.module('pageApp', ['commandAPI']);
function PageCtrl ($scope, $http, commandAPI) {
$scope.checkStatus();
}
angular
.module('pageApp')
.controller('pageAppCtrl', PageCtrl);
})();
</script>
Well it seems that somehow the properties of the app and the controller were applied to two HTML elements within the page. Not sure how that happened but there it was.
I have several html pages, each with an angular app isolated without routing (the app is not a Single Page Application)
//new anguar app in each page
var app = angular.module('app', ['ui.bootstrap', …
My token is stored into the localstorage so to secure the application i've added in each pages this block of code:
app.run(function ($window, $localStorage) {
…
if (!$localStorage.currentUser)
$window.location.href = 'Login.html';
});
This approch seems to work, but does exist a better way considering that no routing is used in this application?
This question may have been asked before. But here goes:
My website is http://thecheeknee.com.
The site basic structure is as follows:
`index.html
js|-app.js
js|ctrls|pageLoad.js -common controller for all pages
js|srvc|Datamap.js
templates/-about.html, etc`
The HTML basic view is as shown below:
<section ui-view></section>
The UI router angular code is as follows:
angular
.module('app',[
'ui.router',
'ngStorage'
])
.config(['$urlRouterProvider','$stateProvider',function($urlRouterProvider, $stateProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home',{
url:'/',
templateUrl:'templates/home.html',
controller:'pageLoad'
})
The controller is very basic.
angular
.module('app')
.controller('pageLoad',[ '$scope', 'Datamap', function($scope, Datamap){
$scope.title = "thecheeknee";
//$scope.$storage = $localStorage;
//$scope.$storage.counter = $scope.$storage.counter+1 || 0;
Datamap.getData().then(function(response){
$scope.datamap = response.data;
});
The Data map service is as follows:
angular.module('app')
.factory('Datamap', function($http) {
//debugger;
return{
getData: function(){
return $http.get('data/data.json',{ cache: true});
}
}
});
The site works perfectly on the desktop across multiple browsers. But Chrome App on Android seems to load a blank page.
(I had designed the site to be responsive and had tested the UI thoroughly using Chrome's browser tool)
On observing, I noticed that the browser adds a #!/ and loads the view into the page. On the mobile browser however, it seems to be stopping at the site name itself (#!/ is not being added). So I assume the UI router is unable to load the route into the page.
I am relatively new to Angular, so is there anything minor I am missing out here?
Full source code at: https://github.com/thecheeknee/sitebase.git
I'm developing a angular app, and this app has about a 10 configurable properties (depending on the environment and client).
I had those properties in json config files, but this is really troublesome: there must be specific builds per env/company. So I would like to retrieve those properties once from the backend on app load.
So in order to do this I created a Provider
var app = angular.module('myApp', [...]);
app.provider('environment', function() {
var self = this;
self.environment;
self.loadEnvironment = function (configuration, $http, $q) {
var def = $q.defer();
$http(...)
.success(function (data) {
self.environment = Environment.build(...);
def.resolve(self.environment);
}).error(function (err) {
...
});
return def.promise;
};
self.$get = function(configuration, $http, $q) {
if (!_.isUndefined(self.environment)) {
return $q.resolve(self.environment);
}
return self.loadEnvironment(configuration, $http, $q);
};
}
app.config(... 'environmentProvider', function(... environment) {
...
//The problem here is that I can't do environment.then(...) or something similar...
//Environment does exists though, with the available functions...
}
How to properly work with this Provider that executes a rest call to populate his environment variable?
Thanks in advance!
This is an excelent scenario to explore angularjs features.
Assuming that you really need the environment data loaded before the app loads, you can use angular tools to load the environment and then declare a value or a constant to store your environment configs before the app bootstraps.
So, instead of using ng-app to start your app, you must use angular.bootstrap to bootstrap it manually.
Observations: You mustn't use ng-app once you are bootstrapping the app manually, otherwise your app will load with the angular default system without respecting your environment loading. Also, make sure to bootstrap your application after declare all module components; i.e. declare all controllers, servieces, directives, etc. so then, you call angular.bootstrap
The below code implements the solution described previously:
(function() {
var App = angular.module("myApp", []);
// it will return a promisse of the $http request
function loadEnvironment () {
// loading angular injector to retrieve the $http service
var ngInjector = angular.injector(["ng"]);
var $http = ngInjector.get("$http");
return $http.get("/environment-x.json").then(function(response) {
// it could be a value as well
App.constant("environment ", response.data);
}, function(err) {
console.error("Error loading the application environment.", err)
});
}
// manually bootstrap the angularjs app in the root document
function bootstrapApplication() {
angular.element(document).ready(function() {
angular.bootstrap(document, ["myApp"]);
});
}
// load the environment and declare it to the app
// so then bootstraps the app starting the application
loadEnvironment().then(bootstrapApplication);
}());
Is there anyway to check when "/" route is called for the first time?
I mean, check when the home page of the app is opened for the first time.
Suppose you have an app that is a Single Page Application, if you want code that runs once, use module.run(): http://docs.angularjs.org/guide/module
angular.module('myModule', []).
run(function($http /*or whatever*/) {
// here goes your code that will only run at module initialization
});
You can use cookies. If user visit your app first time then he have not cookies but next time he will have.
.controller('MainCtrl', function ($scope, $cookies, $cookieStore, $log) {
$scope.showHello = !$cookies.visited;
$cookies.visited = 'yes';
});
view:
<div ng-if"showHello">
Hellow, stranger!
</div>
And don't forget to load ngCookes module
angular.module('App', ['ngCookies']);