I'm getting unknown provider error when i'm trying to use resolve from a state. The object i want returned seems to be returned correctly, so i can't really figure out what the problem is.
This is my first angular project so if I something seems wierd it probably is.
The error: https://docs.angularjs.org/error/$injector/unpr?p0=boardProvider%20%3C-%20board%20%3C-%20AppCtrl
var ponk = angular.module("ponk", ["ui.router", "ngResource"]);
ponk.config(['$stateProvider', '$urlRouterProvider',
"$locationProvider", function ($stateProvider, $urlRouterProvider,
$locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider.state('board', {
url: '/b/:slug',
templateUrl: 'views/board.html',
controller: "AppCtrl",
controllerAs: "pk",
resolve: {
board: function($stateParams, boardFactory) {
var board = {};
if($stateParams.slug) {
board = boardFactory.get({slug:$stateParams.slug}).$promise;
}
return board;
}
}
});
}]).run(function($state) { $state.go('board'); });;
ponk.factory("boardFactory", ["$http", "$resource",
function($http, $resource) {
return $resource('/board/:slug', {slug:'slug'}, {update: { method: "PUT" }});
}]);
ponk.controller("AppCtrl", ["$scope", "$http", "boardFactory", "board",
function($scope, $http, boardFactory, board ) {
console.log(board); // correct object, but error
}]);
EDIT:
discovered the above code works. The problem is when i add this to the controller:
var pk = this;
var pk.board = board;
Related
i already checked on stackoverflow and i see there are duplicate posts, but none of them resolved my issue. The issue with most of the cases is the injection of the $state. But i already injected in my controller above and still having the same issue.
My code:
App.js
var app = angular.module('app', [
'wizardControllers',
'claimDataService',
'ui.router'
]);
app.config(function($stateProvider, $urlRouterProvider){
// Otherwise
$urlRouterProvider.otherwise("/flight-details");
$stateProvider
.state('flight-details', {
url: "/flight-details",
controller: 'FlightDetailsController',
templateUrl: "partials/flight-details.html"
})
.state('flight-problem', {
url: "/flight-problem",
controller: 'FlightProblemController',
templateUrl: "partials/flight-problem.html"
})
});
Controller:
var wizardControllers = angular.module('wizardControllers', ['ngAnimate']);
wizardControllers.controller('FlightDetailsController', ['$scope','$state','$http','claimDataService', function ($scope,$state,$http,claimDataService){
$scope.claim = {};
$scope.claim_data = claimDataService.get();
$scope.nextStep = nextStep;
function nextStep(){
claimDataService.set($scope.claim);
$scope.$state.go("flight-problem");//Giving Me the error
}
}]);
Remove $scope before $state, try this
$state.go("flight-problem");//Working fine
I am able to lazy load angularjs with the help of requirejs. But, how can I load modules that needs to be associated to the controller?
My example configuration in app.js looks like the following, loading all the providers and keeping a reference.
var app = angular.module('myApp', ['ui.router'])
var cacheProviders = {};
app.getProvider = function () {
return cacheProviders.$provide;
}
app.getCompileProvider = function () {
return cacheProviders.$compileProvider;
}
app.getControllerProvider = function () {
return cacheProviders.$controllerProvider;
}
app.getFilterProvider = function () {
return cacheProviders.$filterProvider;
}
app.config(['$stateProvider', '$urlRouterProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
(function () {
cacheProviders.$controllerProvider = $controllerProvider;
cacheProviders.$compileProvider = $compileProvider;
cacheProviders.$filterProvider = $filterProvider;
cacheProviders.$provide = $provide;
})();
var lazyCtrlLoad = function (controllerName) {
return ["$q", function ($q) {
var deferred = $q.defer();
require([controllerName], function () {
deferred.resolve();
});
return deferred.promise;
}];
}
$stateProvider.state('main.view2b', {
url: '/view2b',
templateUrl: 'forms/empl/searchEmplForm.html',
controllerAs: 'srchC',
controller: 'searchEmplCtrl',
resolve: {
loadOtherCtrl: lazyCtrlLoad('searchEmplCtrl')
}
})
In my other module, I am trying to register controllers, load services..
define([
'angular', 'angularResource'
], function (angular) {
angular.module('myApp')
.getControllerProvider()
.register(ctrl, ...)
But, while loading service below, I need access to $resource which is part of ngResource module in angularResource.
angular.module('myApp')
.getProvider().service('deptService', ['$resource', function ($resource) {
return $resource('/dept/:dept', {dept: '#_dept'});
}])
How can I load ngResource while initalizing the javascript controllers/services lazily?
Take a look to AngularAMD here. It allows you to load controllers in the ui-router without using lazyload. This AngularAMD is used to integrate requireJs and Angular.
$stateProvider
.state('home', {
url: '',
views: {
'#': angularAmd.route({
templateUrl: 'ngApplication/application/shared/layouts/basic/basicTplView.html',
controllerUrl: 'ngApplication/application/shared/layouts/basic/basicTplCtrl.js',
controller: 'basicTplCtrl'
}),
'header#home': angularAmd.route({
templateUrl: 'ngApplication/application/shared/layouts/header/headerView.html',
controllerUrl: 'ngApplication/application/shared/layouts/header/headerCtrl.js',
controller: 'headerCtrl'
})
},
});
Also, you are using requirejs, you can load all the dependencies for an specific controller using the define syntax of requireJs. Let's say you want to create a loginCtroller in a separately file, and this controller depends on another angular service:
define(['app', 'transformRequestAsFormPostService'], function (app) {
app.controller('loginCtrl', ['$scope', '$rootScope', '$sce', '$http', '$state', 'transformRequestAsFormPostService', function ($scope, $rootScope, $sce, $http, $state, transformRequestAsFormPost) {
$scope.login = function () {
/*do something here using the service*/
};
}]);
});
Here, the dependency called transformRequestAsFormPostService is another file, I defined it in the main.js (requireJs confifguration file) and it's defined using the same approach than the loginCtrol. Now I am using it in my project and its working so far so good.
Regards,
Ernesto
I have a basic angular setup. I want to add another factory service so that the mainCtrl can use it.
Here is my controller.js
angular.module('Manalator.controllers', [])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Here is my services.js
angular.module('Manalator.services', [])
.factory('cordovaReady', [function () {
return function (fn) {
var queue = [],
impl = function () {
queue.push([].slice.call(arguments));
};
document.addEventListener('deviceready', function () {
queue.forEach(function (args) {
fn.apply(this, args);
});
impl = fn;
}, false);
return function () {
return impl.apply(this, arguments);
};
};
}])
.factory('manaFactory', [function(){
this.testString = function(){
return 'This works';
};
}]);
Here is my routes.js
angular.module('Manalator', ['ngRoute', 'Manalator.services', 'Manalator.controllers'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/main.html'
})
.when('/devotion', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/devotion.html'
})
.when('/results', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/results.html'
})
.otherwise({redirectTo: '/'});
});
I get the following error:
TypeError: Cannot read property 'testy' of undefined
at new <anonymous> (controllers.js:3)
at Object.i [as invoke] (main.min.js:1)
at $get.f.instance (main.min.js:2)
at m (main.min.js:1)
at s (main.min.js:1)
at $get.e (main.min.js:1)
at main.min.js:1
at p.$get.p.$eval (main.min.js:3)
at p.$get.p.$apply (main.min.js:3)
at main.min.js:1
It is a cordova phonegap setup with basic routes. I am new to angular. I have looked over the internet and im having trouble setting up a basic service to hold all my data so i can access it from all my routes. Any help would be appreciated.
You will need to identify your services as a dependency of the controller.
The first step is to make sure you define the services before the controller.
then change the controller code so that it names the services as a dependency.
angular.module('Manalator.controllers', ['Manalator.services'])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Hope this helps!
This is my first attempt to use the Angularjs and I'm trying to create a service and use it inside a controller:
var appTest = angular.module("appTest", ["ngRoute"]);
var appTestControllers = angular.module('appTestControllers', []);
appTest.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
});
$locationProvider.html5Mode(false);
}
]);
appTest.factory("booksApi", function($http){
var _getBooks = function() {
return $http.get('http://localhost/editora-voo/website/books.json');
};
return{
getBooks: _getBooks
};
});
appTest.controller('HomeCtrl', ['$scope', '$http', function($scope, $http, booksApi) {
booksApi.getBooks().success(function(data) {
$scope.books = data;
});
}]);
But it is returning an error: Cannot read property 'getBooks' of undefined
You missed to add booksApi depnedency inside your controller dependency array, You should add it first and then use that inside the function of controller.
Controller
appTest.controller('HomeCtrl', ['$scope', '$http', 'booksApi', //<--missed dependency here
function($scope, $http, booksApi) {
booksApi.getBooks().then(function(response) {
$scope.books = response.data;
});
}]);
Plunkr Here
I am aware that the error which is in the title of this question is basically because in my controller I am injecting a Session service in my controller that has not been defined. I am currently looking at: Angular Devise for which I am rolling out in an application that is using rails but have angular and rails separate. My setup on the angular side is as followed:
main.js
angular.module('App.controllers', []);
angular.module('App.config', []);
angular.module('App.directives', [])
angular.module('App.resources', ['ngResource']);
angular.module('App.services', []);
var App = angular.module("App", [
"ngResource",
"ngCookies",
"$strap.directives",
"App.services",
"App.directives",
"App.resources",
"App.controllers",
"TotemApp.config"
], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "/login";
return;
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
});
Session.js
App.service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = function() {
return $cookieStore.get('_angular_devise_user');
}
this.signedIn = function() {
return !!this.currentUser();
}
this.signedOut = function() {
return !this.signedIn();
}
this.userSession = new UserSession( { email:"sample#email.com", password:"password", remember_me:true } );
this.userRegistration = new UserRegistration( { email:"sample#email.com", password:"password", password_confirmation:"password" } );
}]);
sessions_controller
App.controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save().success(function(data, status, headers, config) {
$cookieStore.put('_angular_devise_user', Session.userSession.email);
$location.path('/todos');
});
}
};
$scope.destroy = function() {
$cookieStore.remove('_angular_devise_user');
$scope.session.$destroy();
};
}]);
routes.js
'use strict';
App.config(function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/sessions/new.html',
controller: 'SessionsController'
})
.when('/sign_up', {
templateUrl: 'views/registrations/new.html',
controller: 'RegistrationsController'
})
.otherwise({
redirectTo: '/'
});
});
This error occurs when I try to access the login page or register page. If someone can shed some light that would be greatly appreciated. Not entirely sure how to resolve this Error: Unknown provider: $SessionProvider <- $Session error
At first glance this looks correct. I can only assume that perhaps you've not included Session.js in your index.html file?
Angular clearly doesn't know what 'Session' service is so there's something wrong there either file not loaded, not loaded correctly or something along those lines as far as I can see.
Edit: Does the error say 'SessionProvider <- Session' or '$SessionProvider -< $session' because if it's the latter, then something is named wrong somewhere in your app since your service is named 'Session' not '$Session'.
When you have syntax error in other javascript or typescript files. You will get the same error. Please make sure that you have no syntax error.