This is the first time I've tried using Angular with Wordpress. I want to inject $location into the config module so I can use it like this:
app = angular.module 'app', [ 'ngResource', 'ngRoute' ]
app.config [ '$routeProvider', '$location', ( $routeProvider, $location )->
$location.hasPrefix '!'
$location.html5Mode true
]
Unfortunately, using $location or $locationProvider with config is causing an Unknown Provider error. I've included all necessary dependencies ie. angular-route.min.js, however, it's still not resolving properly.
If I remove $location it works.
app = angular.module 'app', [ 'ngResource', 'ngRoute' ]
app.config [ '$routeProvider', ( $routeProvider )->
# ROUTES
]
EDIT
If I replace $location with $locationProvider I get Failed to instantiate module app due to: TypeError: Object # has no method 'hasPrefix'
Seems fine if you use the name $locationProvider as the name of the injectable.
Here is a plunker.
And the js:
angular.module('myApp', ['ngResource', 'ngRoute'])
.config(function($routeProvider, $locationProvider) { // provider-injector
$locationProvider.hasPrefix = '!';
$locationProvider.html5Mode = true;
});
For reference from Docs:
Configuration blocks - get executed during the provider registrations
and configuration phase. Only providers and constants can be injected
into configuration blocks. This is to prevent accidental instantiation
of services before they have been fully configured.
The error was a simple typo.
$location.hasPrefix('!');
should be
$location.hashPrefix('!');
Related
I used angular-translate and angular-local-storage with MEANjs, all is add to module dependencies,
in app config.js:
var service = {
applicationEnvironment: window.env,
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: ['ngResource', 'ngAnimate', 'ngMessages', 'ui.router', 'ui.bootstrap', 'ngFileUpload', 'ui-notification',
'LocalStorageModule', 'pascalprecht.translate', 'angularMoment', 'ngFileSaver', 'ngSanitize', 'uiCropper', 'hc.marked'],
registerModule: registerModule
};
and in init.js:
angular
.module(app.applicationModuleName)
.config(localStorageModuleConfig)
.config(transConfig);
localStorageModuleConfig.$inject = ['localStorageServiceProvider'];
function localStorageModuleConfig(localStorageServiceProvider) {
console.log('localStorageModuleConfig');
localStorageServiceProvider
.setPrefix('meanTorrent')
.setStorageType('localStorage')
.setDefaultToCookie(true)
.setNotify(true, true);
}
transConfig.$inject = ['$translateProvider', 'localStorageService'];
function transConfig($translateProvider, localStorageService) {
$translateProvider.useSanitizeValueStrategy(null);
var user_lang = navigator.language || navigator.userLanguage;
user_lang = user_lang.substr(0, 2) || 'en';
var storage_lang = localStorageService.get('storage_user_lang');
user_lang = storage_lang || user_lang;
$translateProvider.preferredLanguage(user_lang);
}
I already include all .js files in html, when runing, I got error Unknown provider: localStorageService,I know in config part, must used provider, but if i used localStorageServiceProvider in transConfig, it can not to .get('storage_user_lang')
any way to used service in config? or how to use provider to call self service`s method?
You can't inject service to configuration block (only providers and constants),
I used window.localStorage to solve this issue localStorage.
I have a Rails app which has some complex routing. My Angular application exists in a deep URL such as /quizzes/1
I was hoping to do this the Angular was by injecting $window into my routes configuration and then sniffing $window.location.pathName. This does not seem possible as the application throws an "Unknown provider: $window from myApp" at this stage.
Is there a best-practice way to handle this with Angular? The reason I would like to do this is to use HTML5 mode while the app lives in a deep directory.
Here's an example of what I was hoping for, http://jsfiddle.net/UwhWN/. I realize that I can use window.location.pathname at this point in the program if it's the only option.
HTML:
<div ng-app="myApp"></div>
JS:
var app = angular.module('myApp', [])
app.config([
'$window', '$routeProvider', '$locationProvider',
function($window, $routeProvider, $locationProvider) {
var path = $window.location.pathname
// Coming Soon
// $locationProvider.html5Mode(true)
$routeProvider
.when(path + '/start', {
controller: 'splashScreenController',
templateUrl: 'partials/splash-screen.html'
})
.when(path + '/question/:id', {
controller: 'questionController',
templateUrl: 'partials/question-loader.html'
})
.otherwise({
redirectTo: path + '/start'
})
}])
Only constants and providers can be injected into config block. $window isn't injectable into your config block because $window is a service.
From Angular docs:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
And, you don't need $window service there anyway. Just use <base> tag:
<base href="/quizzes/1/" />
and keep your routes relative to it.
So this issue only seems to happen when I move a factory to an external file, and I'm really confused as to why. Extracting directives, controllers, and filters to external files does not break my app. I'll show what I'm doing below.
I create my app.js, name the module, inject my various dependencies, continue with my config, and create my factory.
---- app.js -----
angular
.module('myApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',])
.config(function ($routeProvider, $locationProvider, $httpProvider) { ... })
.factory('myFactory', function($http){ ... });
// also works with .factory('myFactory', ['$http', function($http) { ... }]);
I have no issue accessing my factory in my controller this way.
---- controller.js ------
angular.module('myApp')
.controller('myController', function(myFactory){
myFactory.method() // works just fine
});
Alternatively :
---- controller.js ------
angular.module('myApp')
.controller('myController', [ 'myFactory', function(myFactory){
myFactory.method() // also works just fine
}]);
Not sure which syntax is "right" but I try both always and they both work just fine.
...Now, if i remove .factory from app.js and move it to myFactory.js (which is linked in index.html) is where the problem happens.
----- myFactory.js -----
angular.module('myApp')
.factory('myFactory', function($http) { ... }); // also attempted with [ ] syntax
The app now fails to load after refresh, and I receive a pnpr error.
I've attempted:
Removing $http from the factory, and also leaving the factory empty to ensure I wasn't returning bad code from within the factory.
Changing myFactory.js's angular.module to read
angular.module('myFactory', []);
angular.module('myFactory').factory('api', [ '$http', function($http){ ... });
then in app.js injecting 'myFactory' as a dependency... I get some different error all together:
Uncaught Error: [$injector:modulerr] Failed to instantiate module crema.app due to: Error: [$injector:modulerr] Failed to instantiate module myFactory due to: Error: [$injector:nomod] Module 'myFactory' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. errors.angularjs.org/1.3.15/$injector/nomod?p0=myFactory
Loading myFactory.js 1st, 2nd, 9th, last... in index.html, thinking maybe the load order might matter? It did not.
And various other minor syntactical changes. Nothing seems to really help, or change my error.
Not really sure what else to try. Like I said, the factory functions as intended when inside of app.js, and all my controllers, directives, etc. work just fine in external files... just not this factory. Any help would be appreciated.
The problem is that AngularJS does not allow you to register factories after its bootstrap. In order to make it work, you should do the following in your config function:
var app = angular.module('app', [...]);
app.config(function($provide) {
app.factory = function(name, factory) {
$provide.factory(name, factory);
};
});
I have a an angular app and in it I can see this coffee in the app.coffee file....
app = angular.module 'app', [
'ngRoute',
'ngResource',
'ui.router',
'app.filters',
'app.services',
'app.directives',
'app.controllers',
'app.templates',
]
angular.module('app.services', ['ngResource'])
angular.module('app.controllers',[])
angular.module('app.directives', [])
angular.module('app.filters', [])
angular.module('app.templates', [])
angular.module('app.models', [])
I don't really understand why I have to inject ngResource into the app.services module direct AND into the app module. Surely I can just wire up All dependencies into the app module and then it will allow global access to the rest of the modules?
When you write
app = angular.module 'app', [
'ngRoute',
'ngResource',
'ui.router',
'app.filters',
'app.services',
'app.directives',
'app.controllers',
'app.templates',
]
this means these are the dependencies of your app.
When you write
angular.module('app.services', ['ngResource'])
this means app.services has a dependency ngResource. About your question as to why you need to write it again. It is fairly simple, app.services uses ngResource. If you don't want the whole app to have ngResouce dependency, you can ignore it in the first line, but it has to be there for app.services
You can read more about it here
Yet another post about angularjs, minify and ngRoute...
However, I really have no idea why the minified code is failing while the normal version isn't:
I've isolated the issue to this file (appRoutes.js) containing the appRoutes module.
Not Minified:
angular.module('appRoutes', ['ngRoute'])
.config(
['$routeProvider', '$locationProvider', '$httpProvider', '$logProvider',
function($routeProvider, $locationProvider, $httpProvider, $logProvider) {
$routeProvider.when('/', { ... });
$httpProvider.response... );
$locationProvider.html5Mode(true);
$logProvider.debugEnabled(true);
}])
.run(['$rootScope', '$http', function($rootScope, $http){ ... })]);
Minified
angular.module("appRoutes",["ngRoute"])
.config(
["$routeProvider","$locationProvider","$httpProvider","$logProvider",
function(a,d,e,f){
a.when("/",{
etc...
And I'm being given this error:
Unknown provider: aProvider <- a <- $http
Sorry, but I can't figure what the h*ll's wrong with that... ?
The only systematic issue is that the minified version "a" of $routeProvider is the source of the issue... it's just sometimes called b or c...
It works NOT minified, but doesn't work minified...
I tried without the inline annotation.
I tried to use Gulp Closure Compiler and the compiler.jar directly by command line.
I tried to change the order in which the modules are called.
I've got a file called app.js; it's the main angularjs file that calls all dependencies, and appRoutes is in it...
Thaks for your help!