I want to store Url in configuration file so when I deployed this on Testing server or on Production I have to just change the url on config file not in js file but I don't know how to use configuration file in angular js
You can use angular.constant for configurations.
app.constant('appConfigurations', {
link_url: "http://localhost:8080/api",
//For production u can simply change the link_url
//link_url: "http://production_url/api"
});
There are ways you can deal with it , but while coming to our implementation we used to do the following way
Create an External Environment js file
(function (window) {
window.__env = window.__env || {};
window.__env.apiUrl = 'your Api Url';
}(this));
In your Index.html
add env.js above the app.js
<!-- Load environment variables -->
<script src="env.js"></script>
In your app.js
var envr ={};
if(window){
Object.assign(envr,window.__env)
}
// Define AngularJS application var app= angular.module('myapp', []);
// Register environment in AngularJS as constant app.constant('__env',
env);
Update:
For adding additional URl in Config File:
(function (window) {
window.__env = window.__env || {};
window.__env.apiUrl = 'your Api Url';
//Another Url
window.__env.baseUrl ='/';
}(this));
Related
I'm trying to include typical javascript library(JSZip) in to my angularjs application.
At first i have added included JSZip library in to my application and then added script reference to my index page.
Next i have created a simple object of JSZip in one of my module and trying to create zip. but all of sudden, i am getting compilation error in typescript while building my application in VS2015(visual studio), saying that "Cannot find name JSZip".
How to load non angular dependency in angular application. i have spent a complete day. i didn't find any clue.
i have tried multiple ways to get the dependency dynamically and also tried oclazyload to load JSZip dependency ..but not helps.
var zip = new JSZip(); <=== this is where the problem is..
zip.file("File1", atob(response.Data));
zip.file("File2", atob(response.Data));
zip.generateAsync({ type: "blob" })
.then(function (content) {
// saveAs is from FileSaver.js
saveAs(content, "example.zip");
});
Inject non-angular JS libraries
Include the JS file into your HTML file
<script src="http://stuk.github.io/jszip/dist/jszip.js"></script>
In your module angular add constant 'jszip' for exemple
var app = angular.module('myApp', [])
.constant('jszip', window.JSZip)
.run(function($rootScope) {
$rootScope.JSZip = window.JSZip;
})
Inject 'jszip' in your controller, and you will solve your problem
app.controller('myCtrl', function($scope, 'jszip') {
var zip = new jszip();
...
});
For the downloading part (saveAs function), include FileSaver.js into your HTML file
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.js"></script>
In your controller for exemple
$scope.exportZip = function(){
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "example.zip");
});
};
I am using webpack for bundling, and i have 4 module in angularJS(lets assume Management,Student,Teacher and Admin) so i have few js files names common in both management and admin. i am using webpack to create a single "bundle.min.js" file.
Now suddenly i add a feature to admin and i reload the page and find the ui-state router calling management controller insted of calleing admin controller.
my admin config file:
...
.state('admin',{
url:'',
views:{
'main':{
templateUrl:'adminPage.html',
controller:'AdminPageCtrl',
controllerAs:'$admin'},
}
})
...
config of management module
...
.state('management',{
url:'',
views:{
'main':{
templateUrl:'manPage.html',
controller:'AdminPageCtrl',
controllerAs:'$manage'},
}
})
...
admin index.js where i load all config and controllers:
var angular = require('angular'),
config = require('./config'),
adminPageCtrl= require('./controller/AdminPageCtrl');
module.exports = angular
.module('myApp.admin',[])
.controller('AdminPageCtrl', adminPageCtrl)
management index.js i load all config and controllers:
var angular = require('angular'),
config = require('./config'),
adminPageCtrl= require('./controller/AdminPageCtrl');
module.exports = angular
.module('myApp.management',[])
.controller('AdminPageCtrl', adminPageCtrl)
app.js where i load all modules
var angular = require('angular'),
adminModule = require('./admin/index'),
managementModule = require('./management/index'),
angular.module('myApp',['myApp.admin','myApp.management'])
The above is calling AdminPageCtrl of management module, instead of AdminPageCtrl of admin module.
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);
}());
Lets say I have an app, which I don't know it's reference name or where it's defined.
Let's say I have another module which I've created, (nav module) I want to inject this nav module inside the existing angular app so that it can function as normal.
<html ng-app="appA">
<body>
<!-- navController exists inside another app -->
<nav id="testElement" controller="navController"></nav>
</body>
</html>
Example:
$(document).ready(function() {
var nav = document.getElementById('testElement');
if (!angular.element(nav).length) return;
var appElement = angular.element('[ng-app]');
console.log('appname', appElement.attr('ng-app'));
var appToInject;
if (!appElement.length) {
// Manually run the new app from within js without a ng-app attrib
appToInject = angular.module('CustomModuleForNavigation', []);
angular.bootstrap(nav, ['CustomModuleForNavigation']);
} else {
appToInject = angular.module(appElement.attr('ng-app'), []);
}
if (angular.isUndefined(appToInject)) return;
console.log('winning?', appToInject)
appToInject.controller('navController', function($scope) {
console.log('extending app in new ctrl!', $scope);
});
});
When there is an existing app module definition, but you want to add additional dependencies to the app module it can be done this way.
var existingModule = angular.module('appModuleName');
existingModule.requires.push('additionaldependency');
The appModuleName can be found by ng-app attribute of the index.
Make sure this script runs right after the existing module definition script.
Also, scripts required for 'additionaldependency' to be loaded before this script is loaded.
I have figured this out by injecting the dependency into an existing app, or manually running my own up with angular bootstrap.
var appElement = $('[ng-app]').first();
function angularJsModuleMerger(elementToBindScope, dependencies) {
var scopeElement = document.getElementById(elementToBindScope);
// Dependencies should contain our mobile scopeElement app only, the mobile app should contain it's dependencies.
if (!angular.element(scopeElement).length) return;
// If There is an existing angular app, inject our app into it, else, create a new app with our dependencies.
var hasAngularApp = appElement.length;
var appToInject;
if (!hasAngularApp) {
appToInject = angular.module('appForModularInjection', dependencies);
// Manually run this app, so that we're not interrupting the current app.
} else {
// There is an existing app, so let's get it by it's name
appToInject = angular.module(appElement.attr('ng-app'));
// Inject our dependencies to the existing app, IF they don't alreay have these dependencies.
// Dependencies must also be loaded previously.
var currentDependencies = appToInject.requires;
var newDependencies = currentDependencies.concat(dependencies);
appToInject.requires = newDependencies;
appToInject.run(function($rootScope, $compile) {
$compile(angular.element(scopeElement).contents())($rootScope);
});
}
// If we still don't have an app, well, voodoo.
if (angular.isUndefined(appToInject)) return;
// console.log('ok');
// We must run the app after all the declarations above for both existing and non existing apps.
if (!hasAngularApp) angular.bootstrap(scopeElement, ['appForModularInjection']);
}
This will inject it self to an existing app, manually define an app and bind it all correctly to the element in question.
Scope/hierarchy is irrelevant.
I've just started learning Angular and following the tutorial here - http://docs.angularjs.org/tutorial/step_00
I'm downloaded the seed example from GitHub and it works great. I have a question though - if a partial view requires an external js file to be referenced, does it need to be added to the index.html file at the beginning? I want the app to be as lean as possible and only want to include the js references that are required for the present view. Is it possible to load the js files dynamically based on a view?
This just worked for me. Figured I would post it for anybody else seeking the lightest-weight solution.
I have a top-level controller on the page's html tag, and a secondary controller for each partial view.
In the top-level controller I defined the following function…
$scope.loadScript = function(url, type, charset) {
if (type===undefined) type = 'text/javascript';
if (url) {
var script = document.querySelector("script[src*='"+url+"']");
if (!script) {
var heads = document.getElementsByTagName("head");
if (heads && heads.length) {
var head = heads[0];
if (head) {
script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', type);
if (charset) script.setAttribute('charset', charset);
head.appendChild(script);
}
}
}
return script;
}
};
So in the secondary controllers I can load the needed scripts with a call like the following…
$scope.$parent.loadScript('lib/ace/ace.js', 'text/javascript', 'utf-8');
There's a slight delay before the objects contained in the external script are available, so you'll need to verify their existence before attempting to use them.
Hope that saves somebody some time.
I just tried the https://oclazyload.readme.io/. It works out of the box.
bower install oclazyload --save
Load it in your module, and inject the required module in controller:
var myModule = angular.module('myModule', ['oc.lazyLoad'])
.controller('myController', ['$scope', '$ocLazyLoad', '$injector',
function($scope, $ocLazyLoad, $injector) {
$ocLazyLoad.load(
['myExtraModule.js',
'orAnyOtherBowerLibraryCopiedToPublicFolder.js'
])
.then(function() {
// Inject the loaded module
var myExraModule = $injector.get('myExtraModule');
});
}
]);