So I am trying to jump on the Angular bandwagon, and I have been tasked with building an SPA, for which I have selected AngularJS with ASP.Net MVC Web API (I am a .Net developer). As a fan of strongly typed languages, I have avoided javascript whenever possible throughout my career, but frameworks like AngularJS and the other libraries & plugins in recent years have made it impossible to ignore. So here I am, asking for some guidance.
I have watched the tutorials, done the sample code projects and done some learning on PluralSight, and I have things working, at least from a foundational perspective. I have a rich background in MVVM and MVC, so SOC is a big thing for me. I like the MVC type of structure that Angular provides, which is largely why I went this route in the first place.
Now let me get to my issue(s). I am initializing my module (currently) in my master page (_Layout.cshtml), which I did while tweaking and experimenting, for the sake of simplicity.
<script>
angular.module('xcmApp', ['ngRoute', 'ngResource'])
.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'companiesController',
templateUrl: 'views/companylist.html'
})
.when('/Reports',
{
controller: 'reportsController',
templateUrl: 'views/reportlist.html'
})
.otherwise({ redirectTo: '/' })
})
.factory('companiesFactory', ['$resource',
function ($resource) {
return $resource('/api/companies', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}
])
.controller('companiesController', function ($scope, companiesFactory) {
$scope.Companies = companiesFactory.query();
});
</script>
But now that I am ready to move on to deeper concepts, I want to break my scripts out into their appropriate files. Namely, app.js and associated controllers/factories/services etc. However when I move that script into app.js and reference it in _Layout.cshtml, it errors:
<script src="~/app.js"></script>
Error: [$injector:unpr] Unknown provider: a
Now there's no point in continuing to break out into controller files etc. when I can't even get the app.js to work right, so here I am stuck. I know there are some brilliant AngularJS devs on here that probably know what I'm missing before even reading this far, and I am grateful for your assistance.
Anyone who can highlight my oversight will be a superstar for me today. Thanks in advance!
EDIT:
Here is my Stack Trace:
0x800a139e - JavaScript runtime error: [$injector:modulerr] Failed to instantiate module xcmApp due to:
Error: [$injector:unpr] Unknown provider: a
http://errors.angularjs.org/1.3.15/$injector/unpr?p0=a
at Anonymous function (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:4015:13)
at getService (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:4162:11)
at invoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:4191:9)
at runInvokeQueue (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:4109:11)
at Anonymous function (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:4118:11)
at forEach (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:323:11)
at loadModules (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:4099:5)
at createInjector (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:4025:3)
at doBootstrap (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:1452:5)
at bootstrap (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:1473:5)
http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=xcmApp&p1=Error%3A%20%5B%24injector%3Aunpr%5D%20Unknown%20provider%3A%20a%0Ahttp%3A%2F%2Ferrors.angularjs.org%2F1.3.15%2F%24injector%2Funpr%3Fp0%3Da%0A%20%20%20at%20Anonymous%20function%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A4015%3A13)%0A%20%20%20at%20getService%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A4162%3A11)%0A%20%20%20at%20invoke%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A4191%3A9)%0A%20%20%20at%20runInvokeQueue%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A4109%3A11)%0A%20%20%20at%20Anonymous%20function%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A4118%3A11)%0A%20%20%20at%20forEach%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A323%3A11)%0A%20%20%20at%20loadModules%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A4099%3A5)%0A%20%20%20at%20createInjector%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A4025%3A3)%0A%20%20%20at%20doBootstrap%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A1452%3A5)%0A%20%20%20at%20bootstrap%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.js%3A1473%3A5)
REMINDER:
My problem is not that it doesn't work, it DOES WORK. It just STOPS working when I take the Javascript out of my HTML page and place it into a referenced app.js file.
Go back to the documentation. You are using a bad way of defining your application. Try:
var MyApp = angular.module( 'MyApp', ['ngRoute' , 'ngSanitize']) ;
and then use MyApp to add controllers, filters, etc.
EDIT:
BTW, it is a good practice to write the Javascripts in separate files for SPA (you are not writing a small project I guess).
It looks like you are missing a few declaration pieces related to Dependency Injection in your controller definition.
Before I post the specific code and fixes, I want to mention a useful troubleshooting tool for Dependency Injection issues. Angular has a built in directive ng-strict-di. This directive is a companion to ng-app. From the ng-app documentation:
if this attribute is present on the app element, the injector will be created in "strict-di" mode. This means that the application will fail to invoke functions which do not use explicit function annotation (and are thus unsuitable for minification), as described in the Dependency Injection guide, and useful debugging info will assist in tracking down the root of these bugs.
Now, to the code in your post:
Your controller is not using explicit function annotation. In explicit function annotation, you pass a string array of dependencies, followed by the function. This ensures that even if minification were to rename the function parameters, Angular can still identify which dependency to supply to the function. You have used explicit annotation in parts of your code, but it is missing from your controller definition.
This is classically easy to identify, with Error: [$injector:unpr] Unknown provider: a, even though you never defined a provider named a. ng-strict-di would flag this controller code.
Here is the current code, and the proposed fix.
Instead of:
.controller('companiesController', function ($scope, companiesFactory) {
Try:
.controller('companiesController', ['$scope', 'companiesFactory', function ($scope, companiesFactory) {
I don't have an ASP.net background, but I think that souldn't matter to answer your Angular question.
First declare your modules like this:
angular.module('myModule', []);
and get them im oder files like this:
angular.module('myModule').controller/foactory/....
So your code should look something like this:
//xcmApp.module.js
angular.module('xcmApp', ['ngRoute', 'ngResource']);
//xcmApp.config.js
angular.module('xcmApp').config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'companiesController',
templateUrl: 'views/companylist.html'
})
.when('/Reports',
{
controller: 'reportsController',
templateUrl: 'views/reportlist.html'
})
.otherwise({redirectTo: '/'})
});
//xcmApp.factory.js
angular.module('xcmApp').factory('companiesFactory', ['$resource',
function ($resource) {
return $resource('/api/companies', {}, {
query: {method: 'GET', params: {}, isArray: true}
});
}
]);
//xcmApp.controller.js
angular.module('xcmApp').controller('companiesController', function ($scope, companiesFactory) {
$scope.Companies = companiesFactory.query();
});
EDIT:
Regarding the error, keep in mind that your dependencies must be in the rigth order.
So your index.html (assuming you use don't use a script loader yet) should look like this:
<script src="/*path to angular*/"></script>
<script src="/*path to ngRoute*/"></script>
<script src="/*path to ngResource*/"></script>
<script src="/*path to xcmApp.module.js*/"></script> //setting your app module must come first
<script src="/*path to xcmApp.config.js*/"></script>
<script src="/*path to xcmApp.factory.js*/"></script> //must come before the controller in your case
<script src="/*path to xcmApp.controller.js*/"></script>
Related
I am developing an AngularJS application. To ship the code in production, I'm using this Grunt configuration/task:
grunt.registerTask( 'compile', [
'sass:compile', 'copy:compile_assets', 'ngAnnotate', 'concat:compile_js', 'uglify', 'index:compile'
]);
It's really hard to debug, and it's kind of a question to people who already ran into such problems and can point to some direction.
My main module is including those submodules:
angular
.module('controlcenter', [
'ui.router',
'ui.bootstrap',
'templates-app',
'templates-common',
'authentication',
'api',
'reports',
'interceptors',
'controlcenter.websites',
'controlcenter.users',
'controlcenter.campaigns',
'controlcenter.reports',
'controlcenter.login'
])
.run(run);
The error I get is following:
Uncaught Error: [$injector:modulerr] Failed to instantiate module controlcenter due to:
Error: [$injector:modulerr] Failed to instantiate module controlcenter.websites due to:
Error: State 'websites'' is already defined
If I remove the websites module, I get the same error for
controlcenter.users.
I am using the ui-router to handle routing inside the app.
After my build process (for integration testing), everything works just fine:
grunt.registerTask( 'build', [
'clean', 'html2js', 'jshint', 'sass:build',
'concat:build_css', 'copy:build_app_assets', 'copy:build_vendor_assets',
'copy:build_appjs', 'copy:build_vendorjs', 'copy:build_vendorcss', 'index:build', 'karmaconfig',
'karma:continuous'
]);
So maybe ngAnnotate or or concat/uglify are doing weird things here?
UPDATE 1:
It has something to do with my configuration of the modules. Here is the code:
angular
.module('controlcenter.websites',
[
'ui.router'
]
)
.config(config);
config.$inject = ['$stateProvider'];
function config($stateProvider) {
$stateProvider.state( 'websites', {
url: '/websites',
views: {
"main": {
controller: 'WebsitesController',
templateUrl: 'websites/websites.tpl.html'
}
}
});
}
When I change the name of the state to websites_2, I get an error
with 'websites_2 is already defined'.
When I remove the module completely, the next one hast the same problem inside the config file. So is the structure wrong?
Update 2:
The problem seems concat related.
It takes every JS file and adds it one after another to one, bigger file. All of my modules are at the end. The last module always has the problem with 'state already defined'. So it's not just the order of the modules appending to each other, it's something elsse...
Update 3:
I placed my code (I've excluded every Controller-Code and functions, just the scaffold) in a gist. This is the outcome after my compile process, without uglifying it.
Issue:
You have multiple files that contains a config function to configure your module, like this:
angular
.module('controlcenter.websites', [])
.config(config);
function config() {
// ...
}
The problem is that after you concatenate all files you end up with a big file with multiple declarations of config. Because of JavaScript's variable hoisting, all declarations are moved to the top and only the very last of them is evaluated, and this one is:
function config($stateProvider) {
$stateProvider.state( 'websites', {
url: '/websites',
views: {
"main": {
controller: 'WebsitesController',
templateUrl: 'websites/overview/websites.tpl.html'
}
},
data : {requiresLogin : true }
});
}
Hence, each time you .config(config) a module, you are telling Angular to configure your module with that particular configuration function, which means that it executes multiple times and tries to define the state websites more than once.
Solution:
Wrap each JavaScript file code with a closure. This way you will avoid declaring a variable/function more than once:
(function (angular) {
'use strict';
angular
.module('controlcenter.website.details', ['ui.router'])
.config(config);
config.$inject = ['$stateProvider'];
function config($stateProvider) {
$stateProvider
.state( 'websiteDetails', {
url: '/websiteDetails/:id',
views: {
"main": {
controller: 'WebsiteDetailsController',
templateUrl: 'websites/details/website.details.tpl.html'
}
},
data : {requiresLogin : true }
})
.state( 'websiteDetails.categories', {
url: '/categories',
views: {
"detailsContent": {
templateUrl: 'websites/details/website.details.categories.tpl.html'
}
},
data : {requiresLogin : true }
})
;
}
})(window.angular);
Edit:
I strongly recommend you wrap your files into closures. However, if you still don't want to do that, you can name your functions according to their respective modules. This way your configuration function for controlcenter.website.details would become controlcenterWebsiteDetailsConfig. Another option is to wrap your code during build phase with grunt-wrap.
window.angular and closures: This is a technique I like to use on my code when I'm going to uglify it. By wrapping your code into a closure and giving it a parameter called angular with the actual value of window.angular you are actually creating a variable that can be uglified. This code, for instance:
(function (angular) {
// You could also declare a variable, instead of a closure parameter:
// var angular = window.angular;
angular.module('app', ['controllers']);
angular.module('controllers', []);
// ...
})(window.angular);
Could be easily uglified to this (notice that every reference to angular is replaced by a):
!function(a){a.module("app",["controllers"]),a.module("controllers",[])}(window.angular);
On the other side, an unwrapped code snippet like this:
angular.module('app', ['controllers']);
angular.module('controllers', []);
Would become:
angular.module("app",["controllers"]),angular.module("controllers",[]);
For more on closures, check this post and this post.
If you check it in the concatenated file, do you have the states defined twice? Can it be that you are copying the files twice? Check the temporary folders from where you are taking the files (also in grunt config, what you are copying and what you are deleting...).
So I had the same problem but with the following setup:
yeoman angular-fullstack (using typescript)
Webstorm
With the angular-fullstack configuration, the closures were already implemented (as Danilo Valente suggests) so I struggled quite a bit until I found out that in Webstorm, I had the typescript compiler enabled which compiled all of my *.ts files to *.js. But since Webstorm is so 'smart', it does not show these compiled files in the working tree. Grunt however concatenated of course all files regardless if it is typescript of JS. That's why - in the end- all of my states were defined twice.
So the obvious fix: Disabled typescript compiler of webstorm and deleted all the generated *.js files and it works.
I am running through a course at the moment on AngularJS and it has just introduced the concept of routing.
My problem is the app.config function is setup in app.js however, the function doesn't seem to ever be called and therefore the routes are not setup.
The common problem is the ngRoute not being declared however, it is. I'm not sure if there is a problem with the versions of Angular that I'm using but these were taken from the online course.
I have a public plnkr for anyone to view and have a look at http://plnkr.co/edit/L2FG4M?p=preview
(function() {
var app = angular.module("githubViewer", ["ngRoute"]);
app.config(function($routeProvider) {
// If we navigate to /main then the page used will be main.html and the controller
// MainController, if however something else is provided then we will
// redirect to /main as well
$routeProvider.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({
redirectTo: "/main"
});
});
}());
Any help is appreciated, I've exhausted my options now.
Thanks
Marc
In your MainController.js file, you defined a new module with same name as in app.js:
angular.module("githubViewer", []);
What you want to do is retrieve the already defined module. You can acheive that by removing the []:
angular.module("githubViewer");
Look here at the "Creation versus Retrieval" section.
After reading both the api and the developer guide, I still don't understand the functionality provided by declaring 'controller' in a given route. Right now I just have my controllers declared as ng-controller directives in my views. Is ngRoute simply providing an alternative method?
To make my question explicit in code, see below:
--Index.html
...
<body ng-app="MyApp">
<div ng-view>
</div>
</body>
--View.html
<div id="myView" ng-controller="MyController">
...
</div>
--Route.js
var app = angular.module('MyApp', [ require('angular-route') ]);
app.controller('MyController', ['$scope', function ($scope) {
console.log('this gets executed as I would expect');
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', { templateUrl: '/Index.html' })
.when('/view', { templateUrl: '/View.html' });
// below line makes no difference as an alternative to above
//.when('/view', { templateUrl: '/View.html', controller: 'MyController' });
}]);
There are two ways to define controller for a view.
Either in the controller declaration in the ng-route
in the ng-controller for the view.
Either one is fine.
You should pick one option over the other since using both will actually give you duplicate controllers, i.e. both will be used. If you're using Routes, then you can specify a few additional properties such as resolve which has been mentioned in the comments and this will allow you to perform an action, or supply supplementary data etc.
Take a look at this article, Using Resolve In Angular, for more information.
Also, you should look into using Controller As, which sets you up for future proofing. John Papa has a few blogs and videos where he praises the use of Controller As and using the var vm = this; style syntax, take a look here.
Also, as a side note, you should use the .otherwise in your routes as this will capture any requests that are invalid and at least serve up a valid page from your site. You can see this in the routeProvider documentation.
I will try to explain this as concisely as I can.
I have an app that can't be immediately converted to a single angular app. as a result we have a number of seperate modules that are effectively individual apps at the moment and are instantiated on their own relevant pages
Lets say we have two modules A + B both using angular-ui-router to manage state and views, they both access the same rest api but they display the information very differently. However to create or edit a resource in both A + B you use the same form.
This form has a template which can be shared easily but it also has a controller which right now is A.controller('formcontroller'). What is the best way (is there even a way) for me to take that controller away from the A module and inject it into both A + B?
some pseudo code to maybe explain what I am wondering a little clearer
angular.module('A', ['ApiService', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('templateA', {
controller: 'templateACtrl'
})
.state('tempalteA.form', {
controller: 'templateAFormCtrl'
})
})
.controller('TemplateACtrl', function () {
})
.controller('TemplateAFormCtrl', function() {
});
angular.module('B', ['ApiService', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('templateB', {
controller: 'templateBCtrl'
})
.state('tempalteB.form', {
controller: 'templateBFormCtrl'
})
})
.controller('TemplateBCtrl', function () {
})
.controller('TemplateBFormCtrl', function() {
});
I want to get rid of TemplateAFormCtrl and TemplateBFormCtrl and consolodate them into just FormCtrl that can be used by ui-router in both modules
Ok, read the edited example and it can be done in a couple of ways, the best one I can think of (and I will explain why before the solution) is this:
angular.module('formModule', [])
.service('formService', function(){
//Everything that can be abstracted from templateAFormCtrl should be here
});
angular.module('A', ['formModule'])
.config(function($stateProvider, $urlRouterProvider) {
//$stateProvider config
$stateProvider
.state('tempalteA.form', {
controller: 'templateAFormCtrl'
})
})
.controller('TemplateAFormCtrl', function(formService) {
//Assuming you're working with 'controller as' syntax, else attach to $scope
this.formService = formService;
});
angular.module('B', ['formModule'])
.config(function($stateProvider, $urlRouterProvider) {
//$stateProvider config
$stateProvider
.state('tempalteB.form', {
controller: 'TemplateBFormCtrl'
})
})
.controller('TemplateBFormCtrl', function(formService) {
//Assuming you're working with 'controller as' syntax, else attach to $scope
this.formService = formService;
});
Why I would do this? Yeah, you could create a controller on the 'formModule' instead of a service, but you won't be aware of the states of 'A' and 'B' from that controller, and if you later need to react to something that is set on either module or comunicate with any component from it (specially this, since you'll need to inject that component to the 'formModule' hence creating a recursive dependency), you'll have a huge problem.
The way I would do it, allows you to expose every method you want from 'formService' to your views, and on top off that, you'll be able to add code specific to either module on it's own controller.
OLD ANSWER:
The short answer would be:
A factory to manage everything related to API comunications (Requesting/Persisting data to the server)
A service to provide a common API for your controllers, that way you can abstract the methods you want to reuse, and use them on each controller by injecting the service as a dependency.
The longer answer (and I personally recommend you read it, because it will help you a big deal) is this: AngularJS: Service vs provider vs factory
I am currently trying to get in touch with AngularJS. Since I plan to build a rather complex web application I searched for an alternative to the ngView/$routeProvider combination to be found in the ng docs as I find them quite dissatisfying for a complex application with several navigation levels.
So what I tried is to write a custom directive called ngRoute that could be used like this:
<div ng-route="users">
<div ng-route=":id"></div>
<div ng-route></div><!-- default -->
</div>
What I currently have is the following directive definition:
angular.module('app').directive('ngRoute', function($routeProvider) {
var getRoute = function($el) {
var parts = [];
var $curEl = $el;
while($curEl.length > 0) {
parts.unshift($curEl.attr('ng-route'));
$curEl = $curEl.parent().closest('*[ng-route]');
}
return parts.join('/');
}
var directiveDef = {
link: function(scope, $el, iAttrs, controller) {
var route = getRoute($el);
// Register route observer dependant on calculated route...
}
};
return directiveDef;
});
Unfortunately, I get an error due to the DI of the $routeProvider which I need for the registration of the route observation:
Error: Unknown provider: appProvider <- app <- ngRouteDirective
Did I miss something here? Also, feel free to critisize my approach (maybe someone already found a better solution for my problem).
Yeah, I'm not too clear about the approach but shouldn't the dependancy injection be:
angular.module('app')
.directive('ngRoute',['$routeProvider, function($routeProvider) {
// etc,etc...
};
]);
I ended up using the router of the angular-ui project (http://github.com/angular-ui/ui-router)
I find it to be quite satsifying
Unfortunately, I still have no clue why my DI did not work properly
I just ran into this as well using Angular version 1.2.7 (latest as of posting date).
Jumping over to ui-router is tempting but I thought I would offer a work around (albeit a little hacky) that I have working and is stable.
First set up routes as usual, but add $routeProvider to your application:
app.config(function($routeProvider) {
$routeProvider.
when('/a/route/here', {action:"someAction"}).
otherwise({redirectTo:'index'});
app.routeProvider = $routeProvider;
});
Then in the directive add additional routes as needed using:
app.routeProvider.when(...);
Angular adds the new routes and processes them fine when you navigate to them.