Defining angular modules in different files - javascript

I have 3 js files in my application
(mainApp.js, template.js, app.js)
index.html
<html lang="en" ng-app="myapp">
mainApp.js
var app = angular.module('myapp',
['myapp.templateApp', 'myapp.demoApp']);
template.js
angular.module('myapp.templateApp', ['slick', 'localization'])
.controller('CountryLaunguageSelection', [
'$scope', '$rootScope','$http',
function($scope, $rootScope,$http) {
}
]);
app.js
var app = angular.module('myapp.demoApp', [
'ui.router',
'ui.grid',
'ngTouch',
'ui.grid.selection',
'ui.bootstrap',
'ngTable'
]);
app.config(function($stateProvider, $urlRouterProvider) {
});
I need the 3 modules to be in 3 different files.Could anybody tell me what is wrong with the above code.
I am getting the below error
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.28/$injector/modulerr?p0=app&p1=Error%3A%20…0%2FdemoApp%2Ftemplate%2Fthird-party%2Fangular%2Fangular.min.js%3A18%3A387)

Just created such a localhost - it works. Try to compare your index.html and dependencies.
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head lang="en">
<meta charset="UTF-8">
<script src="angular.min.js"></script>
<script src="mainApp.js"></script>
<script src="app.js"></script>
<script src="template.js"></script>
</head>
<body>
<div ng-controller="CountryLaunguageSelection">
{{data.myData}}
</div>
</body>
</html>
mainApp.js
var app = angular.module('myapp', ['myapp.templateApp', 'myapp.demoApp']);
app.js
var app = angular.module('myapp.demoApp', []);
app.config(function() {
});
template.js
angular.module('myapp.templateApp', [])
.controller('CountryLaunguageSelection', [
'$scope', '$rootScope','$http',
function($scope, $rootScope, $http) {
$scope.data = {
myData: "Hello"
};
}
]);

Related

Module Exceptions in Angularjs and $exceptionHandler

In the documentation of Angular 1 for $exceptionHandler it says:
Any uncaught exception in angular expressions is delegated to this service.
https://code.angularjs.org/1.3.20/docs/api/ng/service/$exceptionHandler
Yet when I get a module initialisation error (Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: ...) it does not seem to get logged via the $exceptionHandler.
I want to be able to log these Errors to Sentry via Raven and am having trouble finding a solution to this.
This is an example of what i am trying to achieve:
// Main App module
angular.module('app', ['app.welcome', 'app.contact'])
.factory('$exceptionHandler', [function() {
return function myExceptionHandler(exception, cause) {
// why does the module initialisation error not get caught here..?
console.log("[ERROR] ", exception.message);
};
}]);
// a module I forgot to load..
// app.module('app.contact', []);
// another sub module
angular.
module('app.welcome', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.test = function() {
$window.alert('test');
};
}]);
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="test()">Test</button>
</body>
</html>
Here is a snippet which raise an error because $q is not injected, do whatever you want in custom exception handler.
angular.module('app', []);
angular.
module('app')
.controller('ExampleController', ['$scope', function($scope) {
$scope.test = function() {
$q.when("foo");
};
}])
.factory('$exceptionHandler', [function() {
return function myExceptionHandler(exception, cause) {
console.log("[ERROR] ", exception.message);
};
}]);
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="test()">Raise Error</button>
</body>
</html>

Loading resources with require.js

I want to load or resources in my header with require.js. How can i do this? Here is my current code for my controller and index. I am new to angularjs and will appreciate your help in solving this challenge.
Require.js: located in js/require.js
require.config({
baseUrl: "js",
paths: {
'angular': '.../lib/angular.min',
'angular-route': '.../lib/angular-route.min',
'angularAMD': '.../lib/angular-animate.min.js'
},
shim: { 'angular-animate.min': ['angular'], 'angular-route': ['angular'] },
deps: ['app']
});
Index.html:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>App Demo</title>
<script data-main="js/main" src="js/require.js"></script>
<script src="js/controllers.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="main" ng-view></div>
</body>
</html>
App.js:
define(function () {
var myApp = angular.module('myApp', [
'ngRoute',
'artistControllers'
]);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'partials/list.html',
controller: 'ListContrIndex.htmloller'
}).
when('/details/:itemId', {
templateUrl: 'partials/details.html',
controller: 'DetailsController'
}).
otherwise({
redirectTo: '/list'
});
}]);
return app;
});
Controller.js:
define(['app'], function (app) {
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.artists = data;
$scope.artistOrder = 'name';
});
}]);
artistControllers.controller('DetailsController', ['$scope', '$http','$routeParams', function($scope, $http, $routeParams) {
$http.get('js/data.json').success(function(data) {
$scope.artists = data;
$scope.whichItem = $routeParams.itemId;
if ($routeParams.itemId > 0) {
$scope.prevItem = Number($routeParams.itemId)-1;
} else {
$scope.prevItem = $scope.artists.length-1;
}
if ($routeParams.itemId < $scope.artists.length-1) {
$scope.nextItem = Number($routeParams.itemId)+1;
} else {
$scope.nextItem = 0;
}
});
}]);
});
use data-main="path/file.js" to specify the file to load scripts..
<script data-main="path/file.js" src="js/require.js"></script>
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>App Demo</title>
<script data-main="js/main" src="js/require.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="main" ng-view></div>
</body>
</html>
and in main.js
require.config({
baseUrl: "js",
paths: {
'angular': '.../lib/angular.min',
'angular-route': '.../lib/angular-route.min',
'angularAMD': '.../lib/angular-animate.min.js'
},
shim: { 'angular-animate.min': ['angular'], 'angular-route': ['angular'] },
deps: ['app']
});
require(['requireModule,'requireModule2'],function(requireModule,requireModule2){
//code to start the application
})
Your code doesn't allow to start the application through requirejs . You need to define AngularJS Components as RequireJS Modules
RequireJS loads all code relative to a baseUrl. The baseUrl is normally set to the same directory as the script used in a data-main attribute for the top level script to load for a page. The data-main attribute is a special attribute that require.js will check to start script loading. This example will end up with a baseUrl of scripts:
<!--This sets the baseUrl to the "scripts" directory, and
loads a script that will have a module ID of 'main'-->
<script data-main="scripts/main.js" src="scripts/require.js"/>
For more information on this, check Loading JS Files - Require.js

App is breaking due to factory in angularjs. Why?

I have no idea why this code is breaking...
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"> </script>
<script>
var app = angular.module('test', []);
app.service('mySerivce', function($scope) {
return 0;
});
app.controller('myController', function($scope, myService) {
});
</script>
</head>
<body ng-app='test'>
<div ng-controller="myController">
</div>
</body>
</html>
I am getting the error message:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=myServiceProvider%20%3C-%20myService%20%3C-%20myController
$scope is not available to factories or services. Also I misspelled myService.
Add controller dependency in string array format, like below:
.controller('MyController', ['myService', function (myService) {
}]);
You can refer this in Error: [$injector:unpr]

ui-router not replacing ui-view in index.html

I have set up a basic AngularJS app in VS and cannot get the ui-router functionality working. I have looked at videos, blogs, SO answers and as far as I can tell I am doing everything right, although, I am brand new to web development.
First, here is the solution structure:
and the code...
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<meta charset="utf-8" />
</head>
<body ng-app="app">
<div ui-view></div>
<script src="bower_components/angular/angular.js"></script>
<script src="app/app.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
</body>
</html>
app.js:
(function () {
'use strict';
angular.module('app', ['ui.router']);
})();
app.states.js:
(function () {
'use strict';
angular.module('app')
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/test.html',
controller: 'testCtrl',
controllerAs: 'vm'
})
});
})();
test.html:
<div>
<p>TEST PAGE</p>
</div>
testCtrl.js:
(function () {
'use strict';
angular.module('app')
.controller('testCtrl', testCtrl);
testCtrl.$inject = ['$state'];
function testCtrl($state) {
var vm = this;
var userAuthenticated = false;
init();
function init() {
$state.go('home');
};
};
})();
Can anyone see anywhere I have made a mistake?
There is a working example
I would say, that I miss these lines in your index.html
...
<script src="app/app.states.js"></script>
<script src="templates/testCtrl.js"></script>
That will loade the crucial state definition, and related controller. Check it in action here

Angularjs app not working after adding new controller

Initially my controller.js looked like this
function MyCtrl1() {}
MyCtrl1.$inject = [];
function MyCtrl2() {
}
MyCtrl2.$inject = [];
And the html code like this
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="http://angular-ui.github.com/bootstrap/ui-bootstrap-tpls-0.2.0.js"></script>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
<div ng-view></div>
<div>Angular seed app: v <span app-version></span></div>
<div>Author is : <span app-author></span></div>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
Here is the service.js code
angular.module('myApp.services', []).
value('version', '0.1')
.value('author','Jay');
And the directive.js code
angular.module('myApp.directives', []).
directive('appVersion', ['version', function(version) {
return function(scope, elm, attrs) {
elm.text(version);
};
}])
.directive('appAuthor', ['author', function(author) {
return function(scope, elm, attrs){
elm.text(author);
};
}]);
The above code worked completely worked fine and displayed version and author configured in service.js
The moment i modify my controller.js to include a new controller as below it stops working and nor the version nor the author is displayed.
The modified controller code is as below
function MyCtrl1() {}
MyCtrl1.$inject = [];
function MyCtrl2() {
}
MyCtrl2.$inject = [];
angular.module('myApp', ['ui.bootstrap']);
var TabsDemoCtrl = function ($scope) {
$scope.panes = [
{ title:"Dynamic Title 1", content:"Dynamic content 1" },
{ title:"Dynamic Title 2", content:"Dynamic content 2" }
];
};
TabsDemoCtrl.$inject = ['$scope'];
Any pointers why this thing is not working.
Looks like your problem is the redeclaration of myApp here:
angular.module('myApp', ['ui.bootstrap']);
I was able to reproduce your problem when I had
angular.module('myApp', ['myApp.services', 'myApp.directives']);
angular.module('myApp', ['ui.bootstrap']);
Switching it to
angular.module('myApp', ['myApp.services', 'myApp.directives', 'ui.bootstrap']);
made everything work again.

Categories