Angularjs using $inject doesn't work - angularjs

I started a huge change in my AngularJs code to improve it. I was looking this reference and found it pretty interesting, so i was changing my code to follow thos guides.
When i got to the rout configuration i couldn't make it work.
If i use a .config like the code below, everything works fine.
angular
.module('agApp')
.config(
['$stateProvider', '$urlRouterProvider', '$locationProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.when("/", "/First");
$urlRouterProvider.when("", "/First");
$urlRouterProvider.otherwise("/First");
$stateProvider
.state('first', {
url: "/First",
views: {
"main": {
templateUrl: "app/component/first.html",
controller: 'FirstController',
controllerAs: 'vm'
}
}
})
.state('second', {
url: "/Second",
views: {
"main": {
controller: 'SecondController',
controllerAs: 'vm',
templateUrl: "app/component/second.html"
}
}
})
}]);
But when i try to use the code as recomended on the guide, like this:
angular
.module('agApp')
.config('ConfigRouter', ConfigRouter);
/* #ngInject */
function ConfigRouter($locationProvider,$stateProvider,$urlRouterProvider) {
$urlRouterProvider.when("/", "/First");
$urlRouterProvider.when("", "/First");
$urlRouterProvider.otherwise("/First");
$stateProvider
.state('first', {
url: "/First",
views: {
"main": {
templateUrl: "app/component/first.html",
controller: 'FirstController',
controllerAs: 'vm'
}
}
})
.state('second', {
url: "/Second",
views: {
"main": {
controller: 'SecondController',
controllerAs: 'vm',
templateUrl: "app/component/second.html"
}
}
})
}
Then it stops working and i keep getting this error:
Failed to instantiate module agApp due to: Error: [ng:areq]
Argument 'fn' is not a function, got string
I toke care of the proper injection (at least, I think I did) because the output minified code looks like this:
function ConfigRouter(a,b,c){c.when( [.... rest of the code...] ),ConfigRouter.$inject=["$locationProvider","$stateProvider","$urlRouterProvider"],
On the uglify process I'm using ngAnnotate in this order: concat, ngAnnotate and finaly uglify
Am I missing something here? What may be happening to my code?
Do I need any extra file to enable $inject?
I'm trying to structure my AngularJs this way for the first time. By the way, the functionality of the controllers is not affect (also because there is no injection, just a simple function and name definitions), when i can run the app, the rest is working, the problem starts when I try to use the $inject.

The error says it all: you're providing a string as an argument while it should be a function. That's because config blocks don't have names. It has to be
angular
.module('agApp')
.config(ConfigRouter);

Related

AngularJS ui-route $state, $scope and controller event loading

I'm kinda new with this UI-Route I know it's very powerful but i'm having problem working on it, I have use AngularJS before but not that often and this time i really want to use it so given that my questions goes like this (I've search everywhere regarding this but no luck for me):
The scenario is I have Index.html on that page I have two views
which are "News" and "Testi" both are confined on a div
So knowing that I added App.js (which will contain the initial code for my AngularJS implementation):
var app = angular.module('wrcheese', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/Views/Index.html',
views: {
'main': {
templateUrl: '/Views/App/home.html'
},
'testi': {
templateUrl: '/Views/App/testimonial.html'
}
},
controller: 'HomeCtrl'
})
});
and my controller goes like this (homeController.js)
'use strict';
app.controller('HomeCtrl', function ($scope, $state) {
$scope.welcomeMessage = 'Welcome to WeRCheese';
});
my problem is that I'm trying to access that "welcomeMessage" on my home.html page but wasn't able to, what strange is that when i put in a breakpoint on my controller it wasn't hit it seems the controller does not exist.
Maybe I'm doing it wrong because I don't have any problem when i use ngRoute before.
Lastly, how do you add in a factory?
app.controller('HomeCtrl', function ($scope, $state, homeFactory) {
});
or
app.controller('HomeCtrl', ['$scope', '$state', 'homeFactory', function ($scope, $state, homeFactory) { }]);
TIA.
I was having problem adding a comment my mistake for not realizing that I need to edit my question here. Anyway for my problem I was able to load the controller via different page but I'm still having problem loading the controller on the Index.html i tried updating the .state -> tried on different approach i.e. use '', '/', 'index' in the views.
.state('home', {
url: '', or '/', or 'index',
templateUrl: '/Views/Index.html',
controller: 'HomeCtrl'
But still the controller is not loading, to be specific I have tried adding this line on my Index.html {{ welcomeMessage }} just to verify that the controller was/has been loaded properly.
When you have add views property to a state, the original template, templateUrl properties will be ignored, so you have to bind controllers in views.
$stateProvider.state('home', {
url: '/home',
templateUrl: 'Views/Index.html', <----- will be ignored
views: {
'main': {
templateUrl: 'Views/App/home.html',
controller: 'HomeCtrl'
},
'testi': {
templateUrl: 'Views/App/testimonial.html',
controller: 'HomeCtrl'
}
},
controller: 'HomeCtrl' <----- will be ignored
})
For factory: after defined it, you can inject it by both the ways you posted.
refer this plunker.
var app = angular.module('wrcheese', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
views: {
'main': {
templateUrl: '/Views/App/home.html',
controller : 'HomeCtrl'
},
'testi': {
templateUrl: '/Views/App/testimonial.html',
controller : 'HomeCtrl'
}
},
})
});
you can do this
.state('home', {
url: '/home',
views: {
'#': {
templateUrl: '/Views/Index.html',
controller: 'HomeCtrl',
controllerAs: 'vm'
},
'main#home': {
templateUrl: '/Views/App/home.html'
},
'testi#home': {
templateUrl: '/Views/App/testimonial.html'
}
}
});
using controllerAs is a best practice

Failed to instantiate angularjs module. Because it says it's not using explicit annotation and cannot be invoked in strict mode

I wish to use ng-annotate and the following syntax in my app (using ng-strict-di) to avoid minification issues but I keep getting this error in the console as if I was missing the /** ng#Inject */ comment above the routeConfig function.
What am I missing?
This is the error:
**Uncaught Error: [$injector:modulerr] Failed to instantiate module something due to:
Error: [$injector:strictdi] routeConfig is not using explicit annotation and cannot be invoked in strict mode**
And this is the route config file.
(function () {
'use strict';
angular
.module('something')
.config(routeConfig);
/** #ngInject */
function routeConfig($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'MainController'
})
.state('properties', {
url: '/properties',
templateUrl: 'app/components/properties/properties.html',
controller: 'PropertiesController',
controllerAs: 'properties'
})
.state('properties.map', {
templateUrl: 'app/components/properties-map/properties-map.html'
})
.state('properties.grid', {
templateUrl: 'app/components/properties-grid/properties-grid.html'
})
.state('property', {
url: '/property/:id',
templateUrl: 'app/components/property/property.html',
controller: 'PropertyController',
controllerAs: 'property'
});
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
}
})();
Many thanks for your help.

Ionic controllers alias not working when using sidebar

I have an app built using ionic framework, I follow the instructions on ionicframework learn page and now I am using the native sidemenu. The problem is, I can't use controller alias. Here is a snipet of my app.js with the route config:
angular.module('checklist-atendimento', [
'ionic',
'oc.lazyLoad',
'ngStorage',
'ngCordova',
'ngMask'
])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise('/app/atendimento/1');
$httpProvider.interceptors.push('TratamentoDeErrosService');
$stateProvider
.state('app', {
abstract: true,
url: '/app',
views: {
'conteudo': {
templateUrl: 'app/templates/menu.html'
}
}
})
.state('app.inicio', {
url: '/inicio',
views: {
'menuContent': {
templateUrl: 'app/views/inicio.html',
controller: 'InicioController',
}
}
})
.state('app.atendimento', {
url: '/atendimento/:codMenu',
views: {
'menuContent': {
templateUrl: 'app/views/atendimento.html',
controller: 'AtendimentoController',
controllerAs: 'atendimentoCrl'
}
}
})
});
As you can see, I have 2 states, one without controllerAs (InicioController) and the other using controllerAs (AtendimentoController).
In controller I put
$scope.test ="TEST!!!"
and in the view I put
<b>{{atendimentoCtrl.test}}<b>
Nothing happens, if I use just {{test}}, but the text is shown.
Anyone knows how to do it ?
EDIT:
HERE there is a example of what a talking about:
http://plnkr.co/ohL5HE
Look inside ItemCtrl and inside index.html, on item.html.
I tried use an alias to controller but it don't works.
You need to change
$scope.test ="TEST!!!"
to:
this.test ="TEST!!!"
The issue here is just a typo... This is a controller state
.state('app.atendimento', {
url: '/atendimento/:codMenu',
views: {
'menuContent': {
templateUrl: 'app/views/atendimento.html',
controller: 'AtendimentoController',
controllerAs: 'atendimentoCrl'
}
}
})
where we can see 'atendimentoCrl'. And here is a view statement
<b>{{atendimentoCtrl.test}}<b>
where we can see atendimentoCtrl (compare Ctrl suffix and Crl above)
So, there is missing t in the controllerAs

An error when I add $state service to my references in angularjs module

I have some problems to use $state service on my tutorial project.
Here is my module and config definition:
(function () {
"use strict";
angular.module("gameManagement", ["ui.router", "ngAnimate", "ngResource"])
.config(["$stateProvider", "$urlRouterProvider","$state", function ($stateProvider, $urlRouterPorvider,$state) {
$urlRouterPorvider.otherwise("/game/MultiStepForm/step1");
$urlRouterProvider.otherwise("/game/Home");
$stateProvider
.state("Home", {
url: "/game/Home",
templateUrl: "/app/game/GameView.html",
controller: "GameController",
controllerAs: "vm"
});
$stateProvider
.state("Log", {
url: "/Game/Log",
templateUrl: "/app/Log/GameLogView.html",
controller: "GameLogController",
controllerAs: "vm"
onEnter: function () {
$state.go("MultiStepForm");
}
});
$stateProvider
.state("MultiStepForm.view", {
url: "/Game/MultiStepFormView",
templateUrl: "/app/MultiStepForm/MultiStepFormView.html",
controller: "MultiStepFormViewController",
controllerAs: "MultiStepViewLogic"
})
$stateProvider
.state("MultiStepForm.Edit", {
url: "/Game/MultiStepFormEdit",
templateUrl: "/app/MultiStepFormEdit/MultiStepForm.html",
controller: "MultiStepFormEditController",
controllerAs: "MultiStepEditLogic"
})
}]);
})();
I want to use this row:
$state.go();
for this purpose I add $state service to references but, when I add to
references the $state service I start to get this error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module sensorManagement due to:
Error: [$injector:unpr] Unknown provider: $state
http://errors.angularjs.org/1.4.2/$injector/unpr?p0=%24state
...
Any idea why I get the error above? What am I missing?
You could only access provider inside config phase of angular, $state dependency won't be available inside that phase because $state is provider, and you are already accessing it inside config function by appending Provider prefix like $stateProvider.
If you aim is to redirect the route then you could use $state dependency in run block. Do use $state.go from there
app.run(function($state){
$state.go('somestate')
})
I believe you are missing a resolution in your state. You could try something like this:
$stateProvider
.state("Log", {
url: "/Game/Log",
templateUrl: "/app/Log/GameLogView.html",
controller: "GameLogController",
controllerAs: "vm",
resolve: {$state: '$state'},
onEnter: function ($state) {
$state.go("MultiStepForm");
}
});
See the documentation for more information on how the onEnter and onExit callbacks work. Basically the above question doesn't inject the $state service correctly and thus, is unable to transition state(s) due to the callback lacking access to $state.
You will also want to remove the injection into the config:
.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {

How to make tabs in angularJS have separate controllers?

Right now i am using routeProvider to change between views which works awesome. But now i want to create a view which contains 4 different tabs which should contain 4 different controllers. ive read here that it could be done with stateProvider:
Angular ui tab with seperate controllers for each tab
here is my code:
var WorkerApp = angular.module("WorkerApp", ["ngRoute", 'ngCookies', "ui.bootstrap", "ngGrid", 'ngAnimate', 'ui.router']).config(function ($routeProvider, $stateProvider) {
$routeProvider.
when('/login', {
templateUrl: 'Home/Template/login', resolve: LoginCtrl.resolve
})
.when('/register', { templateUrl: 'Home/Template/register', resolve: RegisterCtrl.resolve })
.when('/', { templateUrl: 'Home/Template/main', resolve: MainCtrl.resolve })
.when('/profile', { templateUrl: 'Home/Template/profile', controller: "ProfileController" })
.when('/contact', { templateUrl: 'Home/Template/contact', controller: "ContactController" })
$stateProvider.state('tabs', {
abstract: true,
url: '/profile',
views: {
"tabs": {
controller: "ProfileController",
templateUrl: 'Home/Template/profile'
}
}
}).state('tabs.tab1', {
url: '/profile', //make this the default tab
views: {
"tabContent": {
controller: "ProfileController",
templateUrl: 'Home/Template/profile'
}
}
})
.state('tabs.tab2', {
url: '/tab2',
views: {
"tabContent": {
controller: 'Tab2Ctrl',
templateUrl: 'tab2.html'
}
}
});
});
but i cant get it really to work because default of routeprovider is set to send over to work because my routeprovider is sending over to "/" on default, which makes "/tabs" invalid. so i cant actully figure out if it is possible to switch to states on specific url. Or change state on specific URL in routeProvider?
I can't tell you for sure exactly what's wrong with the code you've provided, but I'm using Angular UI-Router with the same use case you described, and it's working for me. Here's how I have it configured and how it's different from your configuration:
I don't use $routeProvider at all (none of your $routeProvider.when statements). I'm pretty sure you should not be using $routeProvider since you're using $stateProvider.
I have one use of the $urlRouterProvider with an 'otherwise' statement to specify a default URL:
$urlRouterProvider.otherwise("/home");
My calls to $stateProvider.state is a little different from yours. Here's the one for the parent view of the tabs:
$stateProvider.state('configure', {
url: "/configure",
templateUrl: 'app/configure/configure.tpl.html',
controller: 'ConfigureCtrl'
});
Here's an example of the child state (really the same except for the state name being parent.child format, which you already have in your code; and I added a resolve block but you could have that on the parent as well):
$stateProvider.state('configure.student', {
url: "/student",
templateUrl: 'app/configure/student/configure.student.tpl.html',
controller: 'ConfigureStudentCtrl',
resolve: {
storedClassCode: function($q, user, configureService) {
return configureService.loadMyPromise($q, user);
}
}
});
Also, I'm using version 0.2.8 of Angular UI-Router with version 1.2.9 of Angular. I think this would work with any version of Angular 1.2.0 or later.

Resources