I am experimenting and trying to use the angular.element (jQuery wrapper) inside angular's config() function. However, in the main.js file, as soon as I add the deps under angular, it generates the $injector:modulerr error (where the 1st comment is)
Script tag is placed right before in my html file
<script src="js/vendor/require.min.js" data-main="js/own/main.js"></script>
main.js file
require.config({
baseUrl: "js/vendor/",
paths: {
"jquery": "jquery-2.1.1.min",
"angular": "angular.1.2.9.min"
},
shim: {
"angular": {
deps: ["jquery"], // As soon as I add this, it generates a $injector:modulerr error
exports: "angular"
}
}
});
require(["angular"], function(angular){
angular
.module("app", []) // ng-app="app" already defined in <body>
.controller("appctrl", function($scope){ // ng-controller="appctrl" already defined in <body>
$scope.sample = 1; // this works fine if I don't add deps under angular in require.config
});
});
Error is gone by removing the directive "ng-app='urAppName'" in the html page. The ng-app has to be manually bootstrapped by angular.bootstrap(document.body, ["urAppName"]) AFTER you define your angular module, e.g. angular.module("urAppName", []).controller().....;
Note that you can leave other directives such as ng-controller or your model data such as {{modelName}} in the page.
Related
Maybe I have fundamentally misunderstood how requirejs config works but I thought my configuration below made some libraries global so I could just use them in other files while only having to require and define files that I needed to use within the individual script. However I cannot reference $ (jQuery) in my application code without getting a reference error indicating it is not globally accessible. I've isolated the problem to the simple example below.
My file set up is as follows:
test
|
|-index.html
|-TestApp.js
|-MainApp.js
|-lib
| |-require.js
| |-jquery.js
| |-loadash.js
| |-backbone.js
|-css
|-test.css
The library file versions are RequireJS 2.1.22, jQuery 2.0.3, Loadash 3.10.1 and Backbone 1.2.1. I'm just trying to set up my environment and the approach I am taking is to pass my TestApp.js file to require.js to load the required files and bootstrap the application code in MainApp.js. The script in index.html is as follows:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='css/test.css'/>
</head>
<body>
<div></div>
<script src="./lib/require.js" type="text/javascript" data-main="./TestApp.js"></script>
</body>
</html>
The referenced css script file simply ensured the div is visible as an orange square. See below:
div {
height: 100px;
width: 100px;
background-color: #FA6900;
border-radius: 5px;
}
It's the script line in index.html that then kicks off the application code by passing my configuration file to requirejs. This is the TestApp.js passed across as data-main. The TestApp.js is here:
require.config({
paths: {
'jquery': 'lib/jquery',
'lodash': 'lib/lodash',
'backbone': 'lib/backbone'
},
map: {
'*': {
// Backbone requires underscore. This forces requireJS to load lodash instead:
'underscore': 'lodash'
}
},
shim: {
jquery: {exports: '$'},
underscore: {
deps: ['jquery'],
exports: '_'
},
backbone: {
deps: ['underscore'],
exports: 'Backbone'
},
TestApp: {
deps: ['backbone'],
exports: 'TestApp'
}
}
});
require(['MainApp'], function(MainApp) {
MainApp.run();
});
The file above references the paths to the library files I want to use, I then remap loadash to be loaded when underscore is required (I need some of the extra loadash capability), I then use the shim to ensure the dependancies are correct as the files are loaded. Passing this config file to require.js in the index.html seems to be working as all of the files are showing as loaded in my browser. However the problem seems to be they do not appear to be globally accessible as I thought they would be.
Following the config section the last require call loads the MainApp.js file and calls the exposed run function. The MainApp.js looks like this:
define(function(require) {
var run = function() {
$(document).ready(function() {
$('div').click(function() {
$('div').fadeOut('slow');
});
});
};
return {
run: run
};
});
As far as I understood I should not need to require the files I already mentioned in the require config, I thought they should be loaded and available to this code. This is where I have misunderstood what is going on or have missed a step out. The exposed run function is being called but the first line that calls $ throws the error:
ReferenceError: Can't find variable: $
So my questions are:
What have I got wrong in my thinking?
(or) What am I doing incorrectly?
What should I be doing in order to preload and make available
frequently referenced libraries so that I do not need to require and
define them in every file I have?
As far as I understood I should not need to require the files I already mentioned in the require config, I thought they should be loaded and available to this code.
You misunderstood how RequireJS works. You should read the documentation from start to finish. For now, here are things you should change.
You should require jquery in your MainApp module:
define(function(require) {
var $ = require("jquery");
You should remove your shims that you have for jquery, underscore and backbone as they all call define and shim is only for code that does not call define. I don't know what TestApp is but if it is your own code, you really should make it into a proper AMD module and remove the shim.
#Louis has made me realise the error in what I was doing above. Changing the shim in TestApp.js so that is reads:
MainApp: {
deps: ['backbone'],
exports: 'MainApp'
}
Corrected the problem, now Backbone, $ and _ are all available to the rest of my application code without cluttering up each files require. i.e. I do not need to begin every file with:
define (['lib/jquery', 'lib/loadash', 'lib/backbone'], function($, _ , Backbone) {
Given in my actual app the list of common deps is quite large this means I only need to define locally used resources and can control the paths from a single location.
fter including require tag the application is behaving abnormal way .is there any way i can bootstrap my application apart from below code .
main.js
require(['/module.js'], function() {
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
});
When I written as single file js file the code is working properly.
module.js
var name = 'myApp';
angular.module(name, [])
.controller('Controller', require(['controller.js']))
.factory('Service', require(['service.js']))
.filter('Number', require(['filter.js']));
I have included my main.js in index.html . index html has 3 views i am displaying them based on ng-show from index.html.
The problem is module.js loading properly and js files too. Script is not executing properly so that my entire index.html page including 3 views displayed automatically with error messages.
Control is not going to controller.js/service.js
Error :
Error: Unknown provider: depsProvider <- deps .
Did i miss any define code? Thanks in advance
Angular does not support AMD by default, You need to config angular to export angular object. Please check out the this post for more details.
require.config({
paths: {
'angular': '../lib/angular/angular'
},
shim: {
'angular': {
exports: 'angular'
}
}
});
Your module.js should be defined with define method of requirejs and it should return module.
You can omit file extesion (.js) while using requireJs
There is something really weird going on when I'm using RequireJS with AngularJS. I managed to load all my angular dependencies through RequireJS. I can see those scripts downloaded when I open up the Sources pane in Chrome's developer tool. But Angular keeps throwing an error in the console that it failed to instantiate the module:
Uncaught Error: [$injector:modulerr] Failed to instantiate module MyTestApp due to:
Error: [$injector:nomod] Module 'MyTestApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure...<omitted>...0)
It seems like Angular, when loaded with RequireJS, cannot bind with the ng-app tag in the HTML page. I'm not sure if this is the case but it seems like so to me because when I import angular.min.js manually into the HTML page, it all works fine.
Did I do anything wrong when using RequireJS with Angular? How should I use the two together? Here's how my code look:
index.html
<!doctype html>
<html lang="en" ng-app="MyTestApp">
<head>
<meta charset="utf-8">
<title>AngularJS</title>
<link rel="stylesheet" href="css/style.css"/>
<script data-main="main" src="js/require.js"></script>
</head>
<body>
<div ng-controller="TestController">{{helloMessage}}</div>
</body>
</html>
main.js
require.config({
baseUrl: "scripts/app",
shim: {
"angular": {
exports: "angular"
},
"angular.route": {
deps: ["angular"]
},
"bootstrapper": {
deps: ["angular", "angular.route"]
},
},
paths: {
"angular": "../angular",
"angular.route": "../angular-route",
"bootstrapper": "bootstrapper"
}
});
require(["angular", "angular.route", "bootstrapper"],
(angular, ngRoute, bootstrapper) => {
bootstrapper.start();
}
);
bootstrapper.js
function run() {
app = angular.module("MyTestApp", ["ngRoute"]);
app.controller("TestController", TestController);
console.log(app); //Prints object to console correctly, ie, angular was loaded.
}
Here is how I would do it (DEMO).
In main.js, require angular, your app and maybe a controllers.js and other files:
require(['angular', 'app'], function (app) {
angular.element(document).ready(function () {
angular.bootstrap(document, ['MyTestApp']);
});
});
In app.js, require angular and angular route:
define(['angular', 'angular.route'], function() {
var app = angular.module("MyTestApp", ["ngRoute"]);
return app;
});
This is manual bootstraping and therefore does not need the ng-app tag at all.
I'm currently working on a pretty big application with angular and requirejs and I prefer to load the "big" libraries that are used by the whole app anyway independently from requirejs.
So I load one big file which includes angular, angular-route, requirejs, main.js in the beginning. Or if it makes sense to use a CDN version, load it from there. On the other hand I load every controller, directive, filter and service on request. I currently have 50+ controllers which allready makes a difference in initial load time.
But that all depends on the size of your app.
First you does not need to get a variable from the load of "angular.route". The module will be directly loaded in angular.
I think you should also wait for the dom ready event and also make a requirejs app module that will be in charge of loading all app dependencies:
app/app.js:
define([
"angular",
"angular-route",
"app/controllers",
"app/directives",
[...]
], function(angular){
var app = angular.module('app', [
"ngRoute",
"app.controllers",
"app.directives",
[...]
])
.config([function(){
// app configuration goes here
}]);
return app;
})
main.js
require(["angular", "app/app"],
function (angular, app){
angular.element(document).ready(function() {
angular.bootstrap(document, [app.name]);
});
}
);
I had started writing an app using angularJS. After a few weeks, I suddenly realized that I should have used require JS from the beginning to load my modules. Yes, I know, it was stupid. But it is what it is.
So I've tried to convert my code to suit requireJS now.
This is my main.js
requirejs.config({
baseUrl: "js",
paths: {
jquery:'jquery-1.7.min',
angular: 'angular',
angularRoute:'angular-route',
mainApp:'AngularApp/app'
},
priority:['angular'],
shim:{
angularRoute:{
deps:["angular"]
},
mainApp:{
deps:['angularRoute']
}
}});
require(['angular','angularRoute', 'mainApp'],
function(angular, angularRoute, app)
{
angular.bootstrap(document, ['ServiceContractModule']);
});
This is my app.js
define(['angular',
'angularRoute',
'AngularApp/services',
'AngularApp/directives',
'AngularApp/controllers'],
function(angular, angularRoute, services, directives, controllers)
{
console.log("sup");
var serviceContractModule = angular.module('ServiceContractModule',[ 'ngRoute', services, directives, controllers ]);
serviceContractModule.config(function($routeProvider,$locationProvider) {
$routeProvider.when('/contractNumber/:contractNumbers', {
controller : 'ContractController',
templateUrl : './contractSearchResult',
reloadOnSearch : true
}).when('/serialNumber/:serialNumbers', {
controller : 'SerialController',
templateUrl : './serialSearchResult'
}).when('/QuoteManager',{
controller : 'QuoteManagerController',
templateUrl: './quoteManagerView'
}).when('/QuoteManagerHome',{
controller : 'QuoteManagerController',
templateUrl: './quoteManagerHome'
});
});
return serviceContractModule;
});
This is my directives.js file
define(['angular',
'AngularApp/Directives/tableOperations',
'AngularApp/Directives/line',
'AngularApp/Directives/listOfValues'],
function(
angular,
tableOperations,
line,
listOfValues)
{
var directiveModule = angular.module('ServiceContractModule.directives');
directiveModule.directive('tableoperations', tableOperations);
directiveModule.directive('line', line);
directiveModule.directive('listOfValues', listOfValues);
return directiveModule;
}
)
And this is my services.js file
define(['angular',
'AngularApp/Services/quoteManagerSearch'],
function(angular, quoteManagerSearch)
{
var serviceModule = angular.module('ServiceContractModule.services');
serviceModule.factory('searchRequestHandler', quoteManagerSearch);
return serviceModule;
}
)
When I run my page, the current error I am getting is
Uncaught TypeError: Cannot read property 'module' of undefined directives.js:14
Uncaught TypeError: Cannot read property 'module' of undefined services.js:5
This seems to be happening on this particular line
var directiveModule = angular.module('ServiceContractModule.directives');
I think for some reason, the angular file is not getting loaded. Although when I run the page, I can see all the js files being loaded in the correct order in chrome.
Any ideas guys? Need quick help! Thanks!
Looking at the sources for Angular, I do not see anywhere that it calls RequireJS' define so you need a shim for it. Add this to your shim configuration:
angular: {
exports: "angular"
}
By the way, the priority field in your configuration is obsolete. Either you use RequireJS 2.x which ignores this field because priority is supported only by RequireJS 1.x. Or you use RequireJS 1.x which would honor priority but would ignore the shim field because shim was introduced in 2.x. My suggestion: use RequireJS 2.x and remove priority.
There are 2 possible problems with your setup:
1. You are bootstrapping angular in your main.js and then loading the dependencies.
2. You should be referencing the dependency using string
So, after removing the angular.bootstrap from your main.js, try the following:
app.js
define([
'AngularApp/services',
'AngularApp/directives',
'AngularApp/controllers'],
function()
{
console.log("sup");
var serviceContractModule = angular.module('ServiceContractModule',[ 'ngRoute', 'ServiceContractModule.services', 'ServiceContractModule.directives', '<<Your Controller Module Name>>' ]);
serviceContractModule.config(function($routeProvider,$locationProvider) {
$routeProvider.when('/contractNumber/:contractNumbers', {
controller : 'ContractController',
templateUrl : './contractSearchResult',
reloadOnSearch : true
}).when('/serialNumber/:serialNumbers', {
controller : 'SerialController',
templateUrl : './serialSearchResult'
}).when('/QuoteManager',{
controller : 'QuoteManagerController',
templateUrl: './quoteManagerView'
}).when('/QuoteManagerHome',{
controller : 'QuoteManagerController',
templateUrl: './quoteManagerHome'
});
});
angular.bootstrap(document, ['ServiceContractModule']);
});
Check out angularAMD that I created to help the use of RequireJS and AngularJS:
http://marcoslin.github.io/angularAMD/
In my project I want to use RequireJS and bootstrap my app as follows:
requirejs.config({
baseUrl: 'scripts/vendor',
paths: {
jquery: [
'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min',
'jquery'
],
angular: [
'http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min',
'angular'
],
app: '../app'
}
});
require(['require', 'jquery', 'angular', 'app'], function(require, $, angular, app) {
console.log(require);
console.log($);
console.log(angular);
console.log(app);
});
On my index.html only RequireJS is loaded via script tag, where the RequireJS loads the above code.
What works:
- in my Network monitor I can see that RequireJS, jQuery, Angular and app are loaded
- The console.log messages print correct for require, jQuery and app
The angular object is somehow undefined. But if I don't load it from CDN and use my local load, it works! The local file is a RequireJS wrapper that looks like this:
define(['/components/angular/angular.min.js'], function () {
return angular;
});
How do I get this work with Angular'S CDN? Or does this depend on support from Angular?
First, you are confusing "paths" with "shim"
Path is good, don't go for "shim" behavior. But, you need to make your "paths" proper:
paths: {
jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min',
// NOTE: angular is "plain JS" file
angular: 'http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min',
app: '../app'
}
Then, you need to let go of the need to have something returned to you... Just "use the force, Luke" :) and expect the right globals to be there when you need them:
require(['jquery', 'app', 'angular'], function($, app, thisValueDoesNotMatter) {
// you don't need to wrap "require" Just use global
console.log(require);
console.log($);
console.log(app);
// note, angular is loaded as "plain JavaScript" - not an AMD module.
// it's ok. It returns "undefined" but we just don't care about its return value
// just use global version of angular, which will be loaded by this time.
// because you mentioned it in your dependencies list.
console.log(window.angular);
});