Angular NgResource : Initialize error - angularjs

i have a weird problem regarding angular resource. when i try to define it it causes the app to create an error. i dunno but is this the correct style of defining an angular Resource? tIA
main.js
'use strict';
require.config({
paths: {
jquery: 'libs/jquery/jquery-1.9.1',
angular: 'libs/angular/angular.min',
ngResource: 'libs/angular/angular-resource.min'
},
shim: {
angular: {
exports: 'angular'
},
resource : { deps : ['angular'], 'exports' : 'ngResource'},
}
});
require([
'jquery',
'angular',
//'ngResource',
'app',
'routes',
],
function ($, angular, app, routes) {// set main controller
$(function(){
var $html = $('html');
angular.bootstrap($html, [app['name']]);
$html.addClass('ng-app');
});
});

Just to help out those users who are not familiar with the code above; The code shows RequireJS configuration and initialization structure, and only a small part at the end is the actuall AngularJS code.
You have correctly configured RequireJS to include ngResource before initialization, but you didn't actually tell Angular to use it.
I'm not sure what app['name'] stands for, but your angular bootstrap call should include the ngResource module:
angular.bootstrap($html, ['ngResource']);
And, btw, I don't think you need to add the class ('ng-app') at the end.

In your callback when all resources are loaded, try to explicitly define the modules and dependancies before bootstrapping, like this:
angular.module('fooApp', ['ngResource']); // Module name and list of dependancies.
angular.bootstrap(document, 'fooApp');
There is no need to manually add the ng-app class, when this class is used to do bootraping automatically, witch is not what you want. You want to load the applicatiopns module when all scripts are loaded, with the ngResource module as a dependancy.
Hope this helps.

Related

angular-translate injector:modulerr error

According to an excellent explanation of how to add translation using angular-translate (https://technpol.wordpress.com/2013/11/02/adding-translation-using-angular-translate-to-an-angularjs-app/)
I have a breaking my head error and I'm wondering why that happens? And what am I doing wrong?
Error:
angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.26/$injector/modulerr?p0=app&p1=Error%3A%20…alhost%3A9085%2FScripts%2Fcomponents%2Fangular%2Fangular.min.js%3A18%3A170)
Aim:
Partial loading translations in my entire app
What I've done:
Downloaded (both) via bower and included into the project.
angular-translate
angular-translate-loader-partial
Added them into ReguireJS config file (after Angular)
'angular': '../Scripts/components/angular/angular.min',
'ngAnimate': '../Scripts/components/angular-animate/angular-animate.min',
'ngResource': '../Scripts/components/angular-resource/angular-resource.min',
'ngRoute': '../Scripts/components/angular-route/angular-route.min',
'ngCookies': '../Scripts/components/angular-cookies/angular-cookies.min',
'pascalprecht.translate': '../Scripts/components/angular-translate/angular-translate.min',
'angularTranslate': '../Scripts/components/angular-translate-loader-partial/angular-translate-loader-partial.min'
Added shim:
'pascalprecht.translate': {
deps: ['angular']
},
'angularTranslate': {
deps: ['pascalprecht.translate']
}
In app.js file included dependencies (at the end, after angular stuff):
'pascalprecht.translate',
'angularTranslate',
var app = angular.module('app', ['...',
'pascalprecht.translate',
'angularTranslate' ]);
App.js config
app.config(['$routeProvider', '$locationProvider', '$httpProvider', '$translateProvider', '$translatePartialLoaderProvider',
function ($routeProvider, $locationProvider, $httpProvider, $translateProvider, $translatePartialLoaderProvider) {
Stuff in controllers config:
define(
[
'angular',
'./services/services',
'./controllers/controllers',
'./directives/directives',
'./filters/filters',
'pascalprecht.translate'
],
function(angular) {
'use strict';
var module = angular.module('common', ['common.services', 'common.controllers', 'common.directives', 'common.filters', 'pascalprecht.translate']);
return module;
});
Controller
define(function (require) {
'use strict';
function angularTranslate ($translateProvider, $translatePartialLoaderProvider) {
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '../Translations/locale-{part}.json'
});
$translateProvider.preferredLanguage('en');
}
return angularTranslate;
});
After precisely following above tutorial I still get thi error.
I albo searched in github and stackoverflow but nothing works for me.
Please help!
Short: You dependency management in RequireJS is not correct. The controller's module should require angularTranslate, not pascalprecht.translate.
Long:
At first I would advice you using the official documentation and guide which you will found at https://angular-translate.github.io/
I also recommend using both the latest AngularJS (which is 1.5.x atm) and angular-translate (which is 2.10.x atm).
Additionally, I would also advice using only the non minified versions of libraries because they will give you a much better experience. Minified source files are not for the developer.
And I would also appreciate working demo using JSFiddle, Plnkr or others because they give everyone a running proof of concept/bug.
Said this, it is not clear which version of angular-translate you are using. If you have run bower install angular-translate, you will probably have the latest already -- but the page behind the link you have referenced is made with an older one (about three years old). APIs have changed.
Coming to you actual issue: I would say you have mixed the problems both in AngularJS and RequireJS which leads in such exceptions.
First of all: Your (shim) configuration for RequireJS is misleading/confusing. You should not name the partial loader plugin as angularTranslate.
'angularTranslate': '../Scripts/components/angular-translate-loader-partial/angular-translate-loader-partial.min'
and
'angularTranslate': {
deps: ['pascalprecht.translate']
}
Less confusing would be a name like pascalprecht.translate.partialLoader.
And now the RequireJS module dependency management:
You have defined a shim dependency angularTranslate -> pascalprecht.translate. Whenever the last one will be requested, the first one will be loaded before. That's fine.
You have defined your app depends on both pascalprecht.translate and angularTranslate (which is the partial loader actually). This is fine, but the first one is actually obsolete. It will be available automatically because you have defined the shim dependency already.
However the controller's module only requires the core library pascalprecht.translate.
This means: The dependency management resolver of RequireJS will not wait for the partial loader (no reason it should do this) and therefor it can/will be not available when processing the AJS injections (here: translatePartialLoaderProvider).
Disclaimer: I'm the co-maintainer of the AngularJS plugin angular-translate.
app.js looked like this:
define(
[
...
'pascalprecht.translate',
'angularTranslate',
],
var app = angular.module('app', ['...',
'pascalprecht.translate',
'angularTranslate' ]);
but it should be like:
define(
[
...
'pascalprecht.translate',
'angularTranslate',
],
var app = angular.module('app', ['...',
'pascalprecht.translate' ]);
I've defined submodule angular-translate-loader-partial as normal module and that causes the error. Dependency between both modules (angular-translate and angular-translate-loader-partial) should be made only in requirejs shim.

RequireJs exports 3-rd party dependency to late

I would like to add some plugin to my project based on angular + requirejs.
In my config I do:
shim: {
'angular': {exports: 'angular', deps: ['jquery']},
'angular-strap': {deps: ['angular']},
}
But when I write in my module:
define([
'angular',
'angular-strap'
]
Then I get console error "Uncaught ReferenceError: angular is not defined" in line where angular-strap module is registering
angular.module('mgcrea.ngStrap', [
If I remove angular-strap from define application is loaded properly and in global context I can see 'angular' object.
You have inject angular-strap wrongly. You are supposed to use this syntax instead
angular.module('your_app name', ['deps']);
in your case it will be like this
angular.module('yourApp', ['mgcrea.ngStrap']);

In the ui-router-extras demo, I want to use ng-grid in module1 but it's not working

In my project, I hope the lazy loaded modules can add their own state, so I found the ui-router-extras. It's really useful for me, but when I want to use ng-grid in the lazy loaded module like the module1 in demo, the module1.js file looks like this:
define(['angularAMD', 'ngGrid'], function () {
var app = angular.module("module1", ['ui.router','ngGrid']);
...
and the main.js file looks like this:
require.config({
waitSeconds: 100,
paths: {
"angularAMD": "../../lib/angularAMD",
...
"jQuery": "../../lib/jquery",
"ngGrid": "../../lib/ng-grid-2.0.14.debug"
},
shim: {
"angular": { exports: "angular" },
...
"ngGrid": ["angular", "jQuery"],
},
deps: ["app"]
});
But I got an exception from ng-grid : "Uncaught TypeError: Cannot read property 'factory' of undefined". I found the ng-grid source code where the exception happened:
angular.module('ngGrid.services').factory('$domUtilityService',['$utilityService', '$window', function($utils, $window) {....}
So I found in the lazy loaded module, get module by angular.module('mymodule') returns the undefined. Is there something I forgot to write, or is there another way to use ng-grid or other plugin in the lazy load module with ui-router-extras future?
You need to use the 'ngload' plugin for AngularAMD to load a module on the fly.
Excerpt from the docs:
3rd Party AngularJS Modules
3rd party AngularJS modules, meaning any module created using angular.module syntax, can be loaded as any normal JavaScript file before angularAMD.bootstrap is called. After bootstraping, any AngularJS module must be loaded using the included ngload RequireJS plugin.
define(['app', 'ngload!dataServices'], function (app) {...});
In case you need to load your module using the RequireJS plugin or if you have complex dependecies, you can create a wrapper RequireJS module as below:
define(['angularAMD', 'ui-bootstrap'], function (angularAMD) {
angularAMD.processQueue();
});
In this case, all dependencies will be queued up and when .processQueue() is called, it will go through the queue and copy them into current app using app.register:
https://github.com/marcoslin/angularAMD

How to call module factory from another module in Angular.js?

I have problems with call a factory in one module from another module. I am using angular.js + require.js.
Here is my code
Module 1:
define(['angular', 'app/admin/app.admin', 'app/admin/account/services'], function (angular, app, services) {
app.controller('MainCtrl', ['$scope', 'providerService', function ($scope, providerService) {
$scope.showMe = false;
$scope.provider = providerService.Providers;
}]);
return app;
});
Module 2
define(['angular', 'app/admin/config/index'], function (angular) {
'use strict';
var service = angular.module('app.admin.account.services', []);
service.factory('providerService', ['app.admin.config',
function (config) {
var providers = [
{ name: 'google+', url: config.AUTH_URL + '/google' },
{ name: 'facebook', url: config.AUTH_URL + '/facebook' }
];
return {
Providers: providers
};
}
]);
return service;
});
When i try to call providerService in module 2 from module 1. I got an error say providerService is not there. Can someone tell me what I did wrong here?
Cheers
It is perfectly fine to use RequireJS and AngularJS together, however the term "module" has different meaning between the two and is a little bit confusing when it comes to dependencies.
In RequireJS a "module" is a typical Javascript file that encapsulates a piece of code. You define the dependencies using RequireJS in order to pass in/around other modules as dependencies and ensure correct script load ordering.
In AngularJS the term "module" specifically means an AngularJS "module", which is a container for a number of controller/services/directive etc. declarations.
You use RequireJS to define the order and dependencies of your script files. You then also need to tell Angular which "Angular modules" your module depends on, essentially importing all of the controllers/services/directives along with it.
In 'app/admin/app.admin' make sure you define the dependencies for your AngularJS module by passing in the 'app.admin.account.services' module as a second parameter e.g.
var app = angular.module('app.admin', ['app.admin.account.services']);
That will then import the 'app.admin.account.services' module into your main module making your providerService available for dependency injection.

Where's the Backbone require.js dependency being resolved in this example?

In Addy Osmani's ToDo MVC example for require.js + Backbone: https://github.com/addyosmani/todomvc/blob/gh-pages/dependency-examples/backbone_require/js/main.js, he's using
Backbone.history.start() // line #31
without actually requiring Backbone. How/why does this work? Is the shim enabling this? Or am I missing something obvious?
If you have a look in the code, view/app.js is actually requiring Backbone.
And the backbone shim is exporting the global Backbone variable.
If no other modules will actually require the shim, it won't be loaded, so it won't be accessible.
You can try to remove the 'views/app' requirements in main.js to see for yourself.
As #ChristiMihai mentioned, Backbone created a global Backbone object, correct. Let me give you an example of what I do in my Require.js / Backbone / Handlebars app:
First, I include Require config in <head>:
var require_config = {
baseUrl: "/javascripts",
waitSeconds: 5,
paths: {
'cdnjs': 'http://ajax.cdnjs.com/ajax/libs',
'aspnetcdn': 'http://ajax.aspnetcdn.com/ajax',
'cloudflare': 'http://cdnjs.cloudflare.com/ajax/libs',
'local': '/javascripts'
}
}
if (typeof require !== 'undefined') {
require.config(require_config);
} else {
var require = require_config;
}
After that I bootstrap a require module, e.g:
define([
'app'
],
function() {
console.log('Homepage module');
/*
... this is the meat of your app...
you can add other dependencies beside `app` too
*/
});
Now app is the main dependency which resolves via baseUrl to /javascripts/app.js and includes all necessary deps in order, and looks like this:
define([
'order!cdnjs/json2/20110223/json2',
'order!cloudflare/underscore.js/1.3.1/underscore-min',
'order!cloudflare/backbone.js/0.9.2/backbone-min',
'order!handlebars/handlebars-1.0.0.beta.6.min',
'order!lib/ns',
'bootstrap'
], function(){});

Resources