Hey I am new to requirejs, I am trying to use requirejs with angularjs,but I get struggling with dependencies. The first dependency of angular which is ngRoute, doesn't get loaded.
I get the following error:
angular.min.js:6Uncaught Error: [$injector:modulerr]
I have checked the paths of each files and it seems to be ok.
This is my code:
Index.html
<!DOCTYPE html>
<html>
<head>
<title>RequireJS Example</title>
<script type="text/javascript" data-main="scripts/js/main"
src="scripts/vendor/requirejs/require.js">
</script>
<script type="text/javascript">
require(['main'],function () {
console.log("after load requirejs");
})
</script>
</head>
<body ng-app="app" ng-controller="mainCTRL">
{{title}}
</body>
</html>
main.js
require.config({
baseUrl: 'scripts',
paths:{
'angular': 'vendor/angular/angular.min',
'angular-route': 'vendor/angular/angular-route.min',
'jquery': 'vendor/jquery/jquery-1.12.3.min',
'app' : 'js/app',
'bootstrap':'vendor/bootstrap/js/bootstrap.min',
'bootstrapUI': 'vendor/bootstrap-ui/ui-bootstrap-tpls-1.2.4.min',
'hotkeys': 'vendor/hotkeys.min.js',
'jqueryDataTables': 'vendor/jqueryDataTables/jquery.dataTables.min'
},
shim:{
'jquery': {
exports: 'jquery'
},
'angular': {
exports: 'angular',
deps: ['jquery']
},
'angular-route':{
exports: 'ngRoute',
deps: ['angular']
},
'bootstrap':{
exports: 'bootstrap',
deps:['jquery']
},
'app':{
deps: ['jquery','angular','bootstrap','angular-route']
}
}
});
require(['app'], function(){
angular.bootstrap(document,['app']);
})
app.js
/**
* Module
*
* Description
*/
define(['jquery','angular','bootstrap','angular-route'],function($){
var app = angular.module('app', ['ngRoute']);
app.controller('mainCTRL', ['$scope', function($scope){
$scope.title = "Hello World";
}]);
app.controller('HomeCtrl', ['$scope', function($scope){
$scope.title = "Hello Home";
}])
});
UPDATE:
angular-route is loaded properly using requirejs. The problem is that when I call $routeProvider it doesn't work properly as expected and I get another module errors such as:
angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.3/$injector/modulerr?p0=app&p1=ReferenceErr…0%20at%20http%3A%2F%2F127.0.0.1%3A49849%2Fscripts%2Fjs%2Fmain.js%3A36%3A13
define(['jquery','angular','bootstrap','angular-route'],function($){
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when("/home", angularAMD.route({
templateUrl: 'views/home.html', controller: 'HomeCtrl',
controllerUrl: 'ctrl/home'
}))
});
app.controller('mainCTRL', ['$scope', function($scope){
$("#title").text("I have change the title");
console.log("$('#title').val()",$("#title").text());
$scope.title = "Hello World";
}]);
app.controller('HomeCtrl', ['$scope', function($scope){
$scope.title = "Hello Home";
}])
});
Related
I am using require js in my project to load controllers on demand, I am getting "[ng:areq] Argument 'aboutCtrl' is not a function, got undefined" exception while invoking "aboutCtrl", i have configured "$controllerProvider" to register controller and i see the respective file has been downloaded by require js. I am posting my code as follows
Index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AngularJS SPA</title>
<link href="css/bootstrap.css" rel="stylesheet" />
<script data-main="scripts/main.js" src="scripts/libs/require.js"></script>
</head>
<body>
<div ng-include="'views/shared/_header.html'"></div>
<ui-view></ui-view>
</body>
</html>
main.js
require.config({
baseurl: '/scripts/',
paths: {
'angular': 'libs/angular',
'ui-router': 'libs/angular-ui-router',
'jquery': 'libs/jquery-1.10.2',
'bootstrap': 'libs/bootstrap',
'homeCtrl': "controllers/homeCtrl"
},
shim: {
'ui-router': {
deps: ['angular'],
exports: 'angular'
},
angular: {
exports: 'angular'
},
bootstrap: {
deps: ['jquery']
}
},
deps: ['app']
});
require(["app","bootstrap","homeCtrl"],function (app) {
app.init();
});
app.js
define(['ui-router'], function () {
var app = angular.module("app", ['ui.router']);
app.config(['$controllerProvider', function ($controllerProvider) {
app.registerController = $controllerProvider.register;
} ]);
app.init = function () {
angular.bootstrap(document, ['app']);
};
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("home", {
url: "/",
templateUrl: 'views/home/home.html',
controller: 'homeCtrl'
})
.state("about", {
url: "/about",
templateUrl: 'views/account/about.html',
controller: 'aboutCtrl',
resolve: {
load: ['$q', function ($q) {
var defered = $q.defer();
require(['../scripts/controllers/aboutCtrl'], function () {
defered.resolve();
});
return defered.promise;
} ]
}
});
});
return app;
});
homeCtrl.js
define(['app'], function (app) {
app.controller("homeCtrl", function ($scope) {
$scope.Message = "About Us";
});
});
aboutCtrl.js
define(['app'], function (app) {
app.controller("aboutCtrl", function ($scope) {
$scope.Message = "About Us";
});
});
Error Details
Error: [ng:areq] Argument 'aboutCtrl' is not a function, got undefined
I'm starting off with an empty body element and then dynamically adding HTML that contains an ng-controller attribute. I want to bootstrap the Angular application after that html has been added to the body . This works fine with angular 1.0 but not with 1.3.8. Any ideas why?
require(['angular'], function(angular){
'use strict';
buildDom();
function buildDom(){
$('body').append('<div role="tabpanel" ng-controller="WelcomeController"><span>{{greeting}}</span></div>');
}
var app = angular.module('demo', []);
app.controller('WelcomeController', function($scope) {
$scope.greeting = 'Welcome!';
});
angular.element(document).ready(function() {
angular.bootstrap(document, ["demo"]);
});
});
end result - I see {{greeting}} and not Welcome!
right way of bootstrapping angularjs and requirejs is something like:
'use strict';
require.config({
baseUrl: 'js/',
deps: ['jquery'],
paths: {
jquery: '../lib/jquery.min',
angular: '../lib/angular.min'
},
shim: {
'angular': {
'deps': ['jquery'],
'exports': 'angular'
}
},
priority: [
'angular'
]
});
//https://docs.angularjs.org/guide/bootstrap
window.name = 'NG_DEFER_BOOTSTRAP!';
require([
'angular',
'app'
], function(angular, app) {
'use strict';
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
angular.resumeBootstrap([app['name']]);
});
});
now you should have a separate file called app.js :
define([
'angular',
'services',
'directives',
'controllers'
], function (angular) {
'use strict';
return angular.module('myapp', [
'myapp.services',
'myapp.directives',
'myapp.controllers'
]);
});
Then you should have on each file (services.js, directives.js and controllers.js) each one of your angular components declared.
I'm having difficulties setting up Skrollr using AngularJS & RequirejS.
Some articles suggested to set up Skrollr as a directive and that is the approach that I have been following. Unfortunately, Skrollr is not able to initialize. Specifically, when I try to call the skrollr.init() from the directive I get an error saying that skrollr is not defined.
Below is my code:
directives.js
define(['directivesFactory', 'skrollr'], function(directivesFactory){
directivesFactory.directive('skrollr', [function(){
var directiveDefinitionObject = {
link: function() {
skrollr.init();
}
};
return directiveDefinitionObject;
}]);
});
main.js
(function() {
'use strict';
require.config({
baseUrl: 'js',
paths: {
'angular': 'libs/angular-1.3.9',
'angularRoute': 'libs/angular-route-1.3.9',
'bootstrap': 'libs/modernizr-2.6.2-respond-1.1.0.min',
'jquery': 'libs/jquery-1.11.0.min',
'bootstrapJS': 'libs/bootstrap',
'jqueryElastislide': 'libs/jquery.elastislide',
'jqueryPpCustom' : 'libs/jquerypp.custom',
'modernizrCustom' : 'libs/modernizr.custom.17475',
'skrollr' : 'libs/skrollr.min'
},
shim: {
'angular': {
exports: 'angular'
},
'angularRoute': {
deps: ['angular']
},
'jquery': {
exports: '$'
},
'bootstrapJS': {
deps: ['jquery']
},
'jqueryElastislide':{
deps: ['jquery']
},
'jqueryPpCustom':{
deps: ['jquery']
},
'skrollr': {
exports: 'skrollr'
}
}
});
define('controllersFactory', ['angular'], function(angular) {
return angular.module('app.controllers', []);
});
define('servicesFactory', ['angular'], function(angular) {
return angular.module('app.services', []);
});
define('directivesFactory', ['angular'], function(angular) {
return angular.module('app.directives', []);
});
define('app', [
'angular',
'angularRoute',
'servicesFactory',
'controllersFactory',
'directivesFactory',
],
function(angular) {
return angular.module('app', ['app.services', 'app.controllers', 'app.directives', 'ngRoute']);
}
);
require(['app',
'jquery',
'skrollr',
'bootstrap',
'bootstrapJS',
'jqueryElastislide',
'jqueryPpCustom',
'modernizrCustom'],
function(app,
jquery,
skrollr,
bootstrap,
bootstrapJS,
jqueryElastislide,
jqueryPpCustom,
modernizrCustom) {
require([
'controllers/mainController'
],
function() {
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'templates/main.html', controller: "MainController"}).
otherwise({redirectTo: '/'});
}]);
angular.bootstrap(document, ['app']);
}
);
});
})();
From web inspector, I see that skrollr.min.js is loaded before the directives.js file so I believe the directives should be able to call the functions within skrollr.
Any suggestions would be greatly appreciated - thanks!
define(['directivesFactory', 'skrollr'], function(directivesFactory){
directivesFactory.directive('skrollr', [function(){
var directiveDefinitionObject = {
link: function() {
skrollr.init();
}
};
return directiveDefinitionObject;
}]);
});
You don't seem to have required skrollr here, you need to add the require.
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
I am creating an angular application and would like dynamically load the controller. I see you can use a module called ocLazyLoad (found here https://github.com/ocombe/ocLazyLoad)
Now i am sure i have done everything i need to (obviously done something wrong) but when i try to run my application, nothing loads and the browser just freezes. if i load the controller normally, it works fine and the whole page loads.
Here is some code
app.js
var App = angular.module('MyApp', ['ui.router', 'ngStorage', 'ngCookies', 'pascalprecht.translate', 'oc.lazyLoad']);
config.state.js
App.config(['$stateProvider', '$httpProvider', '$locationProvider', '$urlRouterProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$ocLazyLoadProvider',
function ($stateProvider, $httpProvider, $locationProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $ocLazyLoadProvider) {
'use strict';
// enable html5Mode
$locationProvider.hashPrefix('!').html5Mode(true);
// defaults to home
$urlRouterProvider.otherwise('/admin/settings');
// config ocLazyLoad
$ocLazyLoadProvider.config({
events: true
});
App.controller = $controllerProvider.register;
App.directive = $compileProvider.directive;
App.filter = $filterProvider.register;
App.factory = $provide.factory;
App.service = $provide.service;
App.constant = $provide.constant;
App.value = $provide.value;
// states
$stateProvider
.state('admin', {
url: '/admin',
abstract: true,
controller: 'AdminController',
templateUrl: basePath('admin/admin.html')
})
.state('admin.settings', {
url: '/settings',
controller: 'SettingsController',
templateUrl: basePath('admin/settings/settings.html'),
resolve: {
loadController: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'admin-settings',
files: ['/Scripts/app/components/admin/settings/settings-controller.js']
});
}]
}
});
});
function basePath(uri) {
return '/Scripts/app/components/' + uri;
};
}]);
admin-controller.js
App.controller('AdminController', ['$rootScope', '$scope', '$state', '$localStorage', '$translate', '$timeout', '$window', function ($rootScope, $scope, $state, $localStorage, $translate, $timeout, $window) {
'use strict';
//... some code here
}]);
settings-controller.js
App.controller('SettingsController', ['$scope', function ($scope) {
console.log("settings loaded");
}]);
index.html (using asp.net MVC)
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<title ng-bind="models.helloAngular"></title>
#Styles.Render("~/Content/css")
<link rel="stylesheet" href="~/Content/app.css" />
</head>
<body class="layout-boxed">
<section class="wrapper" ui-view></section>
#Scripts.Render("~/bundles/angular")
#Scripts.Render("~/bundles/angular-translate")
#Scripts.Render("~/bundles/angular-storage")
#Scripts.Render("~/bundles/app")
</body>
</html>
admin.html
<!-- Main section-->
<section>
<!-- Page content-->
<div ui-view autoscroll="false" ng-class="app.viewAnimation" class="content-wrapper">
</div>
</section>
settings.html
<div>here</div>