I recently migrated from ui-router 0.0.1 to 0.2.0. Since the migration, ui-router fails to resolve named dependencies that needs to be injected into a view's controller. Here's the sample code which works fine with ver 0.0.1 but fails in ver 0.2.0
angular.module( 'sample.test', [
'ui.router',
'i18nService'
])
.config(function config($stateProvider) {
$stateProvider.state( 'mystate', {
url: '/mystate',
resolve: {i18n: 'i18nService'},
views: {
'main': {
controller: 'MyCtrl',
templateUrl: 'templates/my.tpl.html'
}
}
});
})
.controller('MyCtrl', ['i18n', function(i18n) {
// fails to resolve i18n
}]);
i18nService is a simple service that return a promise
angular.module('i18nService', [])
.factory('i18nService', ['$http', '$q', function($http, $q) {
var deferred = $q.defer();
$http.get('..').then(..);
return deferred.promise;
}]);
I get the error "Unknown provider: i18nProvider <- i18n" when using v0.2.0
If i change the resolve config to:
resolve: {
i18n: function(i18nService) {
return i18nService
}
},
everything works fine. Is this an expected behaviour, or am I missing some configuration?
Here's the plunker: http://plnkr.co/edit/johqGn1CgefDVKGzIt6q?p=preview
This is a bug that was fixed last month:
https://github.com/angular-ui/ui-router/commit/4cdadcf46875698aee6c3684cc32f2a0ce553c45
I don't believe it's in any currently released version, but you could either get the latest from github or make the change yourself in your js file. It's simply changing key to value in that one line (you can see it in the github commit).
A workarround is to just not change the name for now.... do
resolve :{
i18nService: 'i18nService'
}
Then inject i18nService to your controller instead of i18n. It's a bit of a hack, but it does work (it injects the resolved service not the promise).
Related
I'm currently trying to Unit Test the config of a new AngularJS component. We are using ui-router to handle the routing in our application. We have been able to successfully test it for all our previous components, but the code for all of them was written in plain Javascript. Now that we switched to TypeScript we are having some issues.
This is the TypeScript code where we make the configuration of the module:
'use strict';
// #ngInject
class StatetiworkpaperConfig {
constructor(private $stateProvider: ng.ui.IStateProvider) {
this.config();
}
private config() {
this.$stateProvider
.state('oit.stateticolumnar.stateticolumnarworkpaper', {
url: '/stateticolumnarworkpaper',
params: { tabToLoad: null, groupTabId: null, jurisdiction: null, showOnlyItemsWithValues: false, showOnlyEditableItems: false},
template: '<stateticolumnarworkpaper-component active-tab-code="$ctrl.activeTabCode"></stateticolumnarworkpaper-component>',
component: 'stateticolumnarworkpaperComponent',
resolve: {
onLoad: this.resolves
}
});
}
//#ngInject
private resolves($q, $stateParams, ColumnarWorkpaperModel, ChooseTasksModel, localStorageService) {
// Some not important code
}
}
angular
.module('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper')
.config(["$stateProvider", ($stateProvider) => {
return new StatetiworkpaperConfig($stateProvider);
}]);
This is the Spec file, which is written in Javascript:
describe('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper', function () {
beforeEach(module('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper'));
beforeEach(module('oit'));
var state = 'oit.stateticolumnar.stateticolumnarworkpaper';
it('has a route', inject(function ($state) {
var route = $state.get(state);
expect(route.url).toBe('/stateticolumnarworkpaper');
}));
});
My issue is when executing the line var route = $state.get(state), as the route variable is always null. I could verify that the config() method is being executed, but I'm simply out of ideas as to why route is always null on my test.
Just for reference, this is the configuration of another component, but using Javascript
'use strict';
angular
.module('oit.components.binders.binder.dom_tas.taxaccountingsystem.stateworkpapers.stateworkpapersreview')
.config(stateworkpapersreviewConfig);
function stateworkpapersreviewConfig($stateProvider) {
$stateProvider
.state('oit.binder.taxaccountingsystem.stateworkpapersreview', {
url: '/stateworkpapersreview?reviewType&binderId&year&jurisdiction&chartId&withBalance',
templateUrl: 'components/binders/binder/dom_tas/taxaccountingsystem/stateworkpapers/stateworkpapersreview/stateworkpapersreview.tpl.html',
controller: 'StateworkpapersreviewController',
controllerAs: 'stateworkpapersreviewCtrl',
resolve: {
onLoad: resolves
}
});
function resolves($q, $stateParams, StateTiBinderJurisdictionsModel, WorkpaperModel, localStorageService, StateTiFiltersModel) {
// Some not important code
}
}
As you can see the code is basically the same, but still, I can successfully test this component's config in the way I described, but when I try with the one written in TypeScript I get the error I mentioned.
PD: I'm aware of several similar posts (like this one), but none of them deal with TypeScript, which is my issue.
There is huge difference between the TS snippet and the JS one.
I’m not sure why you are using a class to elite a function? .config suppose to get a function.
You can write the same code as in JS just with .ts suffix, it is a valid TS code.
Then you just can import that config function, pass it all the injectables and test it.
I started my first angular application, and am running into an issue where my "home" module isn't working because of a dependency issue. I don't see any dependency missing that I would need. I am using $stateProvider, and $urlProvider, but I am injecting that into the configuration for the home module, so I'm not sure where the problem would lie ?
Config.$inject = ["$stateProvider", "$urlRouterProvider"];
angular.module('home', []).config(Config)
function Config($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/login',
templateUrl: './views/login.html'
})
}
angular.module('home').controller('loginCtrl', function($scope){
$scope.helloWorld = function(){
console.log("This works!")
}
})
The consoled error:
[$injector:modulerr] http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=home&p1=Error%3A%20…
Since "$stateProvider" and "$urlRouterProvider" providers are not part of the core AngularJS module, you need to inject modules, that have this provides into your home module definition. As far as I know, $stateProvider is from ui router module, so
angular.module('home', ['ui.router']).
...
Keep in mind that you also need to include this Javascript in your HTML file. It is in the angular-ui-router file
<script src="js/angular-ui-router.min.js"></script>
I'm a complete Angular noob and trying to do some fancy stuff quickly, so forgive me if this is a dumb question.
I've created a website that uses routing, and I'm using ui-router for the routing instead of the standard Angular router. The theory is still the same - I have an index.html page in the root of my website which is the "master" or "host" page, and loginView.htm, which is a partial, exists in a separate directory.
The mainController for the project is loaded in the index.html page. Referencing this controller does NOT cause an error or problem.
What I'd like to do, in order to keep code manageable and small, is have the custom controller for a partial page lazy load when I load the partial, and then associate that partial page with the newly loaded controller. Makes sense, right? I don't want to load all the controllers by default, because that's a waste of time and space.
So my structure looks like this (if it matters to anyone):
Root
--app/
----admin/
------login/
--------loginView.html
--------loginController.js
--mainController.js
index.html
This is my loginController code. For testing purposes, I have made the mainController code match this exactly.
var loginController = function ($scope, $translate) {
$scope.changeLanguage = function (key) {$translate.use(key); };
};
angular.module('app').controller('loginController', loginController);
Finally, here is my routing code:
function config($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$urlRouterProvider.otherwise("/admin/login");
$stateProvider
.state('login', {
url: "/admin/login",
templateUrl: "app/admin/login/loginView.html",
controller: loginController,
resolve: {
loadPlugin: function ($ocLazyLoad) {
return $ocLazyLoad.load([
{
name: 'loginController',
files: ['app/admin/login/loginController.js']
}
]);
}
}
})
;
}
angular
.module('app')
.config(config)
.run(function ($rootScope, $state) {
$rootScope.$state = $state;
});
Now - if I remove the whole "resolve" section, and change the controller to "mainController", everything works. The page loads, the buttons work, they call the "changeLanguage" function and everything is wonderful.
But I want the "changeLanguage" feature to reside in the loginController because that's the only page that uses it. So when the code looks like it does above, an error fires("Uncaught Error: [$injector:modulerr]") and the partial page fails to load.
I don't understand what I'm doing wrong, and I'm not finding what I need via Google (maybe I just don't know the right question to ask).
Help?
Looking through the docs I cannot find the name property for ocLazyLoad#load.
Try the following:
resolve: {
loadPlugin: function ($ocLazyLoad) {
return $ocLazyLoad.load(['app/admin/login/loginController.js']);
}
}
Or, pre configure it in a config block:
app.config(function ($ocLazyLoadProvider) {
$ocLazyLoadProvider.config({
modules: [{
name: 'loginController',
files: ['app/admin/login/loginController.js']
}]
});
});
// then load it as:
$ocLazyLoad.load('loginController');
I hit some problems minifying my Angular code so I turned on ng-strict-di
One problem seems to reside in the way I resolve a promise on a route in my app.js config
.when('/:userId', {
templateUrl: 'views/main.html',
controller: 'MyCtrl',
resolve : {
myDependency : function(Cache, Model, $route){
return Cache.getCached( $route.current.params.userId);
}
}
})
Then I inject this resolved promise into the MyCtrl controller
angular.module('myApp')
.controller('MyCtrl',[ 'myDependency', '$scope', '$rootScope', '$timeout', function (myDependency, $scope, $rootScope, $timeout) {
etc...
However I get an error from Angular
[Error] Error: [$injector:strictdi] myDependency is not using explicit annotation and cannot be invoked in strict mode
The problem appears to be traceable to the resolve definition in app.js because I can change the name of 'myDependency' there in the resolve and the error message uses the name from there rather than the name of the dependency in myCtrl. And I am explicitly listing the name of the dependency in the myCtrl controller. The app works, but I cannot minify this code because of the problem with this error.
Follow strict-di for resolve as well. Hope this works!
resolve : {
myDependency : ['Cache', 'Model', '$route', function(Cache, Model, $route){
return Cache.getCached( $route.current.params.userId);
}
]}
I catched the same problem and #Mahesh Sapkal solution was right.
But if look at this in details then my problem was that ng-annotate does not detect correctly that function must be annotated. So I added /#ngInject/ comment and it works now!
app.config(/*#ngInject*/function ($routeProvider) {
$routeProvider
.when('/tables', {
template: templateList,
controller: 'TableListController',
resolve: {
initial: /*#ngInject*/function (tableListControllerInitial) {
return tableListControllerInitial();
}
}
})
Setup
I have a directive that takes a path to a json file as attribute value, loads the json, then instantiates Swiffy:
angular.module('myApp')
.directive('swiffy', function ($http) {
return {
restrict: 'A',
scope: {},
link: function postLink($scope, $element, attrs) {
var stage;
// Listen to angular destroy
$scope.$on('$destroy', function() {
if(stage) {
stage.destroy();
stage = null;
}
});
// Load swiffy json
$http({
method: 'GET',
url: attrs.swiffy
}).success(function(data, status, headers, config) {
stage = new swiffy.Stage( $element[0], data );
stage.start();
}).error(function(data, status, headers, config) {
});
}
};
});
The markup:
<div swiffy="my-animation.json"></div>
I also have a basic routing setup:
angular
.module('myApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/info', {
templateUrl: 'views/info.html',
controller: 'InfoCtrl'
})
.otherwise({
redirectTo: '/'
});
});
The controllers here are empty.
Problem
The json file loads as it should and the Swiffy svg is created just fine. But when i navigate away from a view that has a swiffy directive, angular throws an error and the whole app breaks:
TypeError: Cannot read property '1' of null
at annotate (angular.js:3179:24)
at Object.invoke (angular.js:3846:21)
at angular.js:5580:43
at Array.forEach (native)
at forEach (angular.js:323:11)
at Object.<anonymous> (angular.js:5578:13)
at Object.invoke (angular.js:3869:17)
at angular.js:3711:37
at Object.getService [as get] (angular.js:3832:39)
at addDirective (angular.js:6631:51)
The error is thrown after the '$destroy' event has triggered in the directive, so i know that stage.destroy() has run on the Swiffy object.
The angularjs function that throws the error can be found here https://github.com/angular/bower-angular/blob/7ae38b4a0cfced157e3486a0d6e2d299601723bb/angular.js#L3179
As far as i can tell, annotate() is trying to read the parameters on an anonymous function and fails. I have no errors if i remove the Swiffy instantiation so the errors have to be a result of creating the Swiffy object.
I'm using:
AngularJS 1.2.16
Swiffy runtime version 6.0.2
So far I've tried:
updating to AngularJS version 1.2.17-build.111+sha.19d7a12. (It contains an update to the annotate function but that doesn't fix the problem)
removed 'strict mode' from directive.
removed stage.destroy()
I'd rather not make any changes to the angular.js source (I tried to make angular skip anonymous functions but that broke even more things) and the swiffy runtime is not available un-minified so i'm not sure what is going on in there. Any ideas would be great, thanks.