How to dependency injection using ocLazyLoad - javascript

I'm using ocLazyLoad and I have some external angular libraries (Like Chart.js and pascalprecht.translate) and I need to lazy load them in some routes, as you know, for the common angular module dependency injection should be like:
var angularApp = angular.module('myApp',
['oc.lazyLoad', 'pascalprecht.translate', 'chart.js']);
Now, I just need to lazy loading pascalprecht.translate in one of my controllers and also lazy loading chart.js, in another controller, but I still need to add inject them to myApp module but I don't know how to inject and I do not use $stateProvider
I tried this my controller that I needed chart.js:
//Load here.
//$ocLazyLoad.load('./panel/dist/test.js');
angular.module('myApp', ['chart.js', [
'./panel/dist/static/chart.min.js',
'./panel/dist/static/angular-chart.min.js'
]]);
$ocLazyLoad.load('./panel/dist/static/chart.min.js');
$ocLazyLoad.load('./panel/dist/static/angular-chart.min.js');
But I got this error:
angular-chart.min.js:10Uncaught Error: Chart.js library needs to
included, see http://jtblin.github.io/angular-chart.js/

First, you do not need to inject chart.js in your dependency injection, this should be your module:
var angularApp = angular.module('myApp', [ 'oc.lazyLoad' ]);
Now, you want to have access to some libraries from different controllers (let's say routes), as you said you do not use $stateProvider which means you do not use ui-router (which is a third-party library to work with routes and URLs).
This is my suggestion (just a simple solution):
angularApp.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/home', {
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
store: function ($ocLazyLoad) {
return $ocLazyLoad.load(
{
serie: true,
name: "chart.js",
files: [
"./static/chart.min.js",
"./static/chart-angular.min.js",
]
}
);
}
}
});
$routeProvider.when('/needs-translate', {
templateUrl: 'views/needs-translate.html',
controller: 'translateController',
resolve: {
store: function ($ocLazyLoad) {
return $ocLazyLoad.load(
{
serie: true,
name: "pascalprecht.translate",
files: [
"./static/translate.js"
]
}
);
}
}
});
$routeProvider.otherwise({
redirectTo: '/home'
});
// use the HTML5 History API
$locationProvider.hashPrefix = '!';
$locationProvider.html5Mode(true);
});
By the way, if you are using ui.router, this Github issue would be useful for you

Related

Tried to load angular more than once with MVC4

I installed AngularJs with MVC4 using Nuget package and created a bundle for AngularJS
bundles.Add(new Bundle("~/bundles/scripts")
.Include("~/Scripts/angular.js")
.Include("~/Scripts/jquery-{version}.js"));
In Layout I included it as follow:
#Scripts.Render("/scripts/angular-route.js")
#Scripts.Render("/scripts/loginController.js")
#Scripts.Render("/scripts/routeConfig.js")
routeConfig.js
angular
.module('MyApp', [
'ngRoute',
'MyApp.ctrl.crud',
])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: '/Home/Index',
// controller: 'loginController'
});
$routeProvider.when('/login', {
templateUrl: '/Home/loginPage',
controller: 'crudController'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
loginController.js
angular
.module('MyApp.ctrl.crud', [])
.controller('loginController', [
'$scope',
function ($scope) {
alert("In Login Controller")
}
]);
When I program is display following exception:
WARNING: Tried to load angular more than once.
Why I get this Warning?

Unit-Testing AngularJS: Uncaught Error: [$injector:nomod] Module is not available! and ReferenceError: module is not defined when run Karma

I've a small unitTest in Jasmine run with Karma. But when i run Karma it show errors:
Uncaught Error: [$injector:nomod] Module 'material.controllers' 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.
FAILED Unit: LoginController encountered a
declaration exception
ReferenceError: module is not defined
Here are my source code, config Karma file and unitTest.
karma.conf.js
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'/home/tanpham/Angular/Dev/libs/angular/angular.js',
'/home/tanpham/Angular/Dev/js/**/*.js',
'/home/tanpham/Angular/Dev/js/*.js',
'/home/tanpham/Angular/Test/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
index.html
<body ng-app="material" ng-controller="AppController">
<ui-view></ui-view>
</body>
app.js
angular.module('material.controllers', []);
angular.module('material.services', []);
angular.module('material.directives',[]);
angular.module('material.filters',[]);
var app = angular.module('material', ['ui.router','material.directives','http-auth-interceptor','material.controllers','material.services','material.filters'])
.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "views/app.html"
}).state('login', {
url: "/login",
templateUrl: "views/login.html",
controller: "LoginController"
});
$urlRouterProvider.otherwise('/login');
})
loginController
angular.module('material.controllers').controller('LoginController', function($scope) {
$scope.name = "Ari";
$scope.sayHello = function() {
$scope.greeting = "Hello " + $scope.name;
}
});
helloSpec.js
describe('Unit: LoginController', function() {
// Load the module with LoginController
beforeEach(module('material.controllers'));
var ctrl, scope;
// inject the $controller and $rootScope services
// in the beforeEach block
beforeEach(inject(function($controller, $rootScope) {
// Create a new scope that's a child of the $rootScope
scope = $rootScope.$new();
// Create the controller
ctrl = $controller('LoginController', {
$scope: scope
});
}));
it('should create $scope.greeting when calling sayHello',
function() {
expect(scope.greeting).toBeUndefined();
scope.sayHello();
expect(scope.greeting).toEqual("Hello Ari");
});
})
So, i can do with that and my module's name is right?
Check the order in which the angular modules are loaded. As your listing of javascript files in karma conf, see if the module defined files are loaded first before other files that use it.
Adjust the order in this listing, are explicitly load the file where 'material.controllers' module is defined.
files: [
'/home/tanpham/Angular/Dev/libs/angular/angular.js',
'/home/tanpham/Angular/Dev/js/**/*.js',
'/home/tanpham/Angular/Dev/js/*.js',
'/home/tanpham/Angular/Test/*.js'
],
i have met this issue. and solved it.
just add ",[]" behind the module name in the module declare statement。 in this case chaged code will be :
angular.module('material.controllers',[])
.controller('LoginController', function($scope) {
$scope.name = "Ari";
$scope.sayHello = function() {
$scope.greeting = "Hello " + $scope.name;
}
});

Should I instantiate a submodule in large angular apps

I am building a large angular app comprised of various modules
- app
-- member
--- newMember
--- memberDashboard
-- linguistics
-- etc
--- etc etc
In the html I am instantiating individual modules, because I believe there to be a performance improvement over bootstrapping the entire app.
<div ng-app="linguistics">
<div ui-view autoscroll="true"></div>
</div>
However, this means that I have to repeat myself in module configuration. i.e.:
angular.module('linguistics', [
'ui.router',
'ui.bootstrap',
'googlechart',
'babelServices',
'babelFilters'
]).config(function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
$locationProvider.html5Mode(true);
}).config(function($provide) {
return $provide.decorator('$uiViewScroll', function($delegate, $window) {
return function(uiViewElement) {
//eventually do something more intelligent with the uiViewElement
return $window.scrollTo(0, 0);
};
});
});
html5Mode, scrollTo etc will be repeated across modules. Is there a better way to do this?
I'd add a configuration module, that will handle the grunt work of setting up html5Mode, scrollTo etc.
angular.module('configuration', ['ui.router'])
.config(function ($locationProvider, $provide) {
$locationProvider.html5Mode(true);
// For angular 1.3
$locationProvider.html5Mode({
enabled: true,
requireBase: /* true/false */
});
$provide.decorator('$uiViewScroll', function ($delegate, $window) {
return function (uiViewElement) {
return $window.scrollTo(0, 0);
}
});
});
And then in your subsequent modules:
angular.module('linguistics', ['configuration']);

Angular applications powered by Requirejs - Argument '(contoller)' is not a function, got undefined?

I am trying to work on an Angular application powered by RequireJS, but I am not able to split up the controller files as I keep getting an error of Argument '(contoller)' is not a function, got undefined. Any idea what have I done wrong?
app/main.js,
require.config({
baseUrl: "",
// alias libraries paths. Must set 'angular'
paths: {
'domReady': 'bower_components/requirejs-domready/domReady',
'angular': 'bower_components/angular/angular',
'angular-route': 'bower_components/angular-route/angular-route',
'jquery': 'bower_components/jquery/dist/jquery'
},
// Add angular modules that does not support AMD out of the box, put it in a shim
shim: {
'angular': {
exports: 'angular'
},
'angular-route': {
exports: 'angular'
}
},
// kick start application
deps: ['app/bootstrap']
});
app/app.js,
define([
'angular',
'angular-route',
'jquery'
], function (ng,ngRoute,$) {
'use strict';
console.log($('h1').length);
return ng.module('app', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'view/home.html',
controller: 'HomeCtrl',
controllerUrl: 'app/home'
});
$routeProvider.when('/view1', {
templateUrl: 'view/view1.html',
controller: 'View1Ctrl',
controllerUrl: 'app/view'
});
//$routeProvider.otherwise({redirectTo: '/home'});
}]);
});
app/home.js,
define(['app/app'], function (app) {
app.controller('HomeCtrl', function ($scope) {
$scope.message = "Message from HomeCtrl";
});
});
error,
Error: [ng:areq] Argument 'HomeCtrl' is not a function, got undefined
But if I concat the controllers after ng.module('app', ['ngRoute']).config(...) then they work fine,
app/app.js,
define([
'angular',
'angular-route',
'jquery'
], function (ng,ngRoute,$) {
'use strict';
console.log($('h1').length);
return ng.module('app', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'view/home.html',
controller: 'HomeCtrl',
//controllerUrl: 'app/home'
});
$routeProvider.when('/view1', {
templateUrl: 'view/view1.html',
controller: 'View1Ctrl',
//controllerUrl: 'app/view'
});
//$routeProvider.otherwise({redirectTo: '/home'});
}]).controller('HomeCtrl', function ($scope) {
$scope.message = "Message from HomeCtrl";
}).controller('View1Ctrl', function ($scope) {
$scope.message = "Message from View1Ctrl";
});
});
Why??
This seems to be a problem with the load order of your JS files. You are defining the HomeCtrl in app/home.js and using it it app/app.js. So make sure that home.js is loaded before app.js in your web app.
Split the app.js into two parts - one for just creating the ng.module (module.js), and one for setting the config (module-config.js). Then the dependency tree will be:
app/module-config.js
requires: app/home.js
requires: app/module.js

How to link to different page using Angular framework in my case?

I am using angular to provide the link for my page.
I have something like
//main app configuration
app.js
'use strict';
angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives'
]).
config(['$routeProvider', function($routeProvider) {
}]);
//test page configuration
test-controller.js
angular.module('myApp', []).
config(function ($routeProvider) {
$routeProvider.
when('/test/:link', {
templateUrl: 'test/:link.html',
constroller: 'Ctrl'
}).
when('/test2/:link', {
templateUrl: 'test2/:link.html',
constroller: 'Ctrl'
})
}).
controller('Ctrl', ['$scope', function ($scope) {
//scope data
}])
for some reason, the $routeprovide in my test-controller.js doesn't work and output module injection error.
Can anyone help me about it? Thanks a lot!
At first glance, it is because you didn't add 'ngRoute' as dependency in the second definition

Categories

Resources