Loading resources with require.js - javascript

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

Related

How to use modal in angularjs ui?

I'm trying to use Angular UI modal, but I keep getting an unknown provider error message: "Error: [$injector:unpr]".
I use custom build to minimize the overall size of the file. I have injected the ui dependency in the app when creating it. The build files are added to the index.html page.
//This is the app.js file
(function() {
angular.module('locatorApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']);
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home/home.view.html',
controller: 'homeCtrl',
controllerAs: 'vm'
})
.when('/about', {
templateUrl: '/common/views/genericText.view.html',
controller: 'aboutCtrl',
controllerAs: 'vm'
})
.when('/location/:locationid', {
templateUrl: '/locationDetail/locationDetail.view.html',
controller: 'locationDetailCtrl',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}
angular
.module('locatorApp')
.config(['$routeProvider', '$locationProvider', config]);
})();
//This is the controller file
(function() {
angular
.module('locatorApp')
.controller('locationDetailCtrl', locationDetailCtrl);
/*Inject $routeParams service into controller to protect from minification*/
locationDetailCtrl.$inject = ['$routeParams', '$uibModal', 'locatorData'];
function locationDetailCtrl($routeParams, $uibModal, locatorData) {
var vm = this;
vm.locationid = $routeParams.locationid;
locatorData.locationById(vm.locationid)
.success(function(data) {
vm.data = {
location: data
};
vm.pageHeader = {
title: vm.data.location.name
};
})
.error(function(e) {
console.log(e);
});
vm.popupReviewForm = function() {
alert("Let's add a review");
};
}
})();
<!-- This is the index.html file-->
<!DOCTYPE html>
<html ng-app="locatorApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocatoR</title>
<link rel="stylesheet" href="/bootstrap/css/amelia.bootstrap.css">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body ng-view>
<script src="/angular/angular.min.js"></script>
<script src="/lib/angular-route.min.js"></script>
<script src="/lib/angular-sanitize.min.js"></script>
<script src="/lib/ui-bootstrap-custom-2.5.0.min.js"></script>
<script src="/lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
<script src="/angular/locator.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/
jquery.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/javascripts/validation.js"></script>
</body>
</html>
//This is the locatorData service
(function() {
/*Data service for pulling data from the API*/
locatorData.$inject = ['$http'];
function locatorData($http) {
var locationByCoords = function(lat, lng) {
return $http.get('/api/locations?lng=' + lng + '&lat=' + lat + '&maxdist=20');
};
var locationById = function(locationid) {
return $http.get('/api/locations/' + locationid);
};
return {
locationByCoords: locationByCoords,
locationById: locationById
};
};
angular
.module('locatorApp')
.service('locatorData', locatorData);
})();
you should use ng-view on a div inside <body>, so script tags will exist after route template is substituted. Then it would be better to reorganize order of script tags you are adding.
At first non-angular script files, then angular, then your sources
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/javascripts/validation.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/angular/angular.min.js"></script>
<script src="/angular/locator.min.js"></script>
<script src="/lib/angular-route.min.js"></script>
<script src="/lib/angular-sanitize.min.js"></script>
<script src="/lib/ui-bootstrap-custom-2.5.0.min.js"></script>
<script src="/lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
Then use $uibModal service that you've injected:
vm.popupReviewForm = function() {
$uibModal.open({
template: '...html',
//...config from docs
}).then(function(){console.log('closed successfully');})
.catch(function(){console.log('dismissed modal');});
};
Move your script tag either to below of head tag.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocatoR</title>
<link rel="stylesheet" href="/bootstrap/css/amelia.bootstrap.css">
<link rel="stylesheet" href="/stylesheets/style.css">
// Scripts
</head>
or, outside the ng-view :
<body>
<div ng-view></div>
// scripts here
</body>
Ok, I've finally figured it out. The problem was using incompatible versions of Angular JS and Angular UI.

Angular ng-view in Cordova not work

I am noob to angular and Cordova. I am developing a cordova application. I have the following code:
app.js:
var myApp = angular.module('myApp', ['ngSanitize', 'ngAnimate', 'ngRoute']).
config(function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController'
})
.when('/register', {
templateUrl: '/register.html',
controller: 'registerController'
})
.otherwise({
redirectTo: '/home.html'
})
})
.run(['$rootScope', '$location', 'authProvider', function ($rootScope, $location, authProvider) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!authProvider.isLoggedIn()) {
alert('login');
$location.path('/login')
}
});
}]).
factory('authProvider', function () {
var user;
return {
setUser: function (aUser) {
alert('set user');
user = aUser;
},
isLoggedIn: function () {
alert('is loged in');
return (user) ? true : false;
}
};
});
And my index.js is as below:
var app = {
initialize: function () {
this.bindEvents();
},
bindEvents: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function () {
app.receivedEvent('deviceready');
angular.bootstrap(document, ['myApp']);
},
receivedEvent: function (id) {
console.log('Received Event: ' + id);
}
};
app.initialize();
And my index.html is as below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<!--Shared Scripts-->
<script type="text/javascript" src="js/shared/jquery.min.js"></script>
<script type="text/javascript" src="js/shared/angular.js"></script>
<script type="text/javascript" src="js/shared/angular-route.min.js"></script>
<script type="text/javascript" src="js/shared/angular-animate.min.js"></script>
<script type="text/javascript" src="js/shared/angular-sanitize.min.js"></script>
<!--Custom Scripts-->
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/homeController.js"></script>
<script type="text/javascript" src="js/loginController.js"></script>
<title></title>
</head>
<body>
<div ng-view></div>
<script type="text/javascript" src="cordova.js"></script>
</body>
</html>
When I emulate my app in browser(cordova emulate browser), every thing is OK and ng-view works nicely, but when I run it on android device(cordova run android), ng-view does not work!
I have also tried to add :
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
to my app.js, but no success! I have also tried to define my html and body as below:
<html ng-app='myApp'>
or
<body ng-app='myApp'>
But no success !
I am using AngularJs 1.5.8 and Cordova 6.2.0 and running my app on Android 4.0
Updated
After inspecting a Android 5.0 device, I found out that there is an error that saying:
Failed to load resource: net::ERR_FILE_NOT_FOUND file:///login.html
Error: [$compile:tpload] Failed to load template: /login.html (HTTP
status: -1 )
Would you please help me solve this problem?
Thank you
I finally find the solution.
Just moving my views(login.html and home.html) into a folder(for example views) and add dot before my UrlTemplate
$routeProvider
//define the routes and their corresponded controllers
.when('/home', {
templateUrl: './views/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: './views/login.html',
controller: 'loginController'
})
.when('/register', {
templateUrl: './views/register.html',
controller: 'registerController'
})
.otherwise({
redirectTo: './views/home.html'
})

Defining angular modules in different files

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"
};
}
]);

Angular + Requirejs - each data is repeated twice?

I am running Angular under Requirejs, but I have this multiple occurrence where the data in the controller class is repeated twice. Unless I remove ng-app="myApp" from the div. Why?
welcomeController.js,
define(['app'], function (app) {
app.controller('welcomeController', ['$scope', function($scope) {
//your minsafe controller
$scope.message = "Message from WelcomeController";
console.log($scope.message); // it is repeated twice here.
}]);
});
HTML,
<head>
<link rel="stylesheet" href="style.css">
<script data-main="scripts/main.js" src="scripts/vendors/requirejs/require.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="welcomeController">
{{message}}
</div>
</div>
</body>
main.js,
require.config({
//baseUrl: "",
// alias libraries paths. Must set 'angular'
paths: {
'domReady': 'vendors/requirejs-domready/domReady',
'angular': 'vendors/angular/angular',
'angular-route': 'vendors/angular-route/angular-route',
'jquery': 'vendors/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'
}
}
});
define([
'controllers/welcomeController',
'bootstrap'
]);
bootstrap.js,
define([
'require',
'angular',
'app'
], function (require, ng) {
'use strict';
require(['domReady!'], function (document) {
ng.bootstrap(document, ['myApp']);
});
});
app.js,
define([
'angular'
], function (ng) {
'use strict';
//For single module retrun.
return ng.module('myApp', []);
});
But it works ok on Angular without Requirejs. I don't need to remove remove ng-app="myApp" from the div. Why?
<head>
<link rel="stylesheet" href="style.css">
<script src="scripts/vendors/angular/angular.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('welcomeController', ['$scope', function($scope) {
$scope.message = "Message from WelcomeController";
console.log($scope.message); // It occurs only once.
}]);
</script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="welcomeController">
{{message}}
</div>
</div>
</body>
What have I done wrong under Requirejs with Angular?
You are bootstrapping Angular twice: once with the ng-app directive and once with the ng.bootstrap(...) code in bootstrap.js! Go either for automatic (ng-app) or for manual (angular.bootstrap) bootstrapping.
Also, like Josep mentioned in his (deleted) answer, it is better to shim angular-route as:
shim: {
'angular-route': {
deps: ['angular']
}
}
This is NOT the cause of the problem, but will prevent potential future problems (i.e. route being loaded before Angular).
angular-require-lazy may contain some useful ideas for Angular-RequireJS integration with lazy loading

Integrating AngularJS with RequireJS

Due This Article I try to create an application with AngularJS and RequireJS!
I can load angular library... create module and export it to external files! It's ok!
But the problem is I can't create configuration and controllers for my module both in main application file and external files!
Another issue is I can't load views and controllers in app.js via $routeProvider!!
(Sorry for grammer problems!)
app.js:
require.config({
baseUrl: "/angularjs/js",
paths: {
"angular": "libs/angular.min"
},
shim: {
"angular": {
exports: "angular"
}
}
});
define('app', ['angular'], function(angular){
var app = angular.module('myApp', []);
app.config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
controller: 'HomeCtrl'
templateUrl: 'views/home.html'
});
});
return app;
});
require(["app", "controllers/homeController"]);
controllers/homeController.js:
require(["app"], function(app) {
app.controller("HomeCtrl",
function($scope) {
$scope.message = "Hello World!";
}
);
});
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8" />
<title>Angular.js</title>
<script type="text/javascript" data-main="js/" src="js/libs/require.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
views/home.html:
<div ng-controller="HomeCtrl">
<h1>{{messge}}</h1>
</div>
Here is my version of your example. With a few changes it works fine.
It is better to bootstrap AngularJs application manually, when RequireJs.
I separated app.js file in two: main.js - with configuration of RequireJs and app.js - with AngularJs module declaration. Later, this module is used by homeController for declaration of controller. Then, the controller is required in main.js and the application is bootstrapping.
I do the angular and requireJS integration placing NG_DEFER_BOOTSTRAP! flag and have separate files for my app config and routing like in:
require.config({
baseUrl: 'js/',
paths: {
angular: '../lib/bower_components/angular/angular.min',
angularRoute: '../lib/bower_components/angular-route/angular-route.min'
},
shim: {
'angular': {
'exports': 'angular'
},
'angularRoute':{
'deps': ['angular']
}
},
priority: [
'angular'
]
});
//https://docs.angularjs.org/guide/bootstrap
window.name = 'NG_DEFER_BOOTSTRAP!';
require([
'angular',
'app',
'routes'
], function(angular, app, routes) {
'use strict';
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
angular.resumeBootstrap([app['name']]);
});
});
app.js:
define([
'angular',
'filters',
'services',
'directives',
'controllers',
'animations',
'angularRoute'
], function (angular) {
'use strict';
return angular.module('myapp', [
'ngRoute',
'ngCookies',
'ngAnimate',
'myapp.services',
'myapp.directives',
'myapp.filters',
'myapp.controllers',
'myapp.animations'
]);
});
and routes.js:
define(['angular', 'app'], function(angular, app) {
'use strict';
return app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
otherwise({
redirectTo: '/home'
});
}])
});
hope this helps in your scenario.

Categories