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");
});
};
Related
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));
I've just installed the following package with bower:
https://github.com/urish/angular-spinner
The package is added successfully. I've also added:
<script src="bower_components/spin.js/spin.js"></script>
<script src="bower_components/angular-spinner/angular-spinner.js"></script>
When I try to inject it like this:
(function()
{
angular.module('employeeApp',['angularSpinner']).controller('schoolController', schoolController);
It crashes and I receive the error:
Argument 'indexController' is not a function, got undefined
When I remove ['angularSpinner'] everything works again.
What should I do?
--EDIT--
indexController
angular.module('employeeApp').controller('indexController', indexController);
function indexController($location, authenticationFactory,constants)
{
var vm = this;
vm.setName = function()
{
return constants.firstname;
}
}
in angular you create module for your app and there you specify the dependencies. and once you create controller or service you get the module by name and create controller\ service in that module.
//create module for app
angular.module('employeeApp', [ /*add your dependencies here*/ ]);
//create controller\ service
angular.module('employeeApp').controller(function(){
//controller implementation
});
what might happen is you may re initialize your app by mistake.
for simplification you could store your angular module in a variable as follows:
var app = angular.module('employeeApp', ['angularSpinner']);
and define a controller like this:
app.controller('indexController',function(angularSpinner){
//controller code here
});
I am creating a NodeJS app which uses AngularJS for it's front-end. I am Also using RequireJS to load in the JS dependencies and then instantiate the Angular app. Here is what I am trying to do:
Within my HTML file (written in Jade) I include the RequireJS files and then call the RequireJS config using the 'data-main' attribute:
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(type="text/javascript" src="/bower_components/requirejs/require.js" data-main="/main.js")
My main.js file looks as follows:
"use strict";
function(require) {
require(['/assets/requiredPathsAndShim.js'], function(requiredPathsAndShim) {
require.config({
maps : {
// Maps
},
paths : requiredPathsAndShim.paths,
shim : {
// Modules and their dependent modules
}
});
angular.bootstrap(document, ['appNameInHere']);
});
})(require);
I have an external file which contains an object with my routes '/assets/requiredPathsAndShim.js' and it looks like follows:
"use strict";
(function(define) {
define([], function() {
return {
paths : {
'angular' : '/bower_components/angular/angular'
}
};
});
})(define);
I will add that my NodeJS/Express app has the 'bower_components' folder set to serve static files and this is working fine.
Whenever I try and instantiate the AngularJS app using the 'angular.bootstrap...' method it tells me Angular is not defined. I can't see why this is happening and haven't been able to figure it out yet. O can't see any problem with my routes to the Angular files. Can anyone see or suggest why this may be happening?
Thanks!
Just managed to crack it! I had to place the 'angular.bootstrap' call in a callback function of the require.config method as the app was trying to call AngularJS before it had been defined.
Hope this helps anyone in the future.
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');
});
}
]);