Resolve function not being injected in controller [Angular JS] - javascript

angular
.module('madkoffeeFrontendApp', [])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/articles.html',
controller: 'MainCtrl',
resolve: {
articles: function(articleService,$q) {
// return articleService.getArticles();
return 'boo';
}
}
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
My above code contains the resolve.
angular.module('madkoffeeFrontendApp')
.controller('MainCtrl', ['$scope',
function($scope, articles) {
console.log(articles);
}]);
When I tried to inject articles in the array as shown below, it gives an error but as far as I know that's the correct way to inject a resolve function:
angular.module('madkoffeeFrontendApp')
.controller('MainCtrl', ['$scope','articles',
function($scope, articles) {
console.log(articles);
}]);
My articles resolve function is not being injected. I tried returning just a string (example: 'boo') as shown to test if articles dependency works or not, and it doesn't i.e. it returns undefined. What could be the reason?

Here's a Plunker to demonstrate the resolve message. As you'll see in the example, it's the same structure as the code you posted and should work fine.
Click the about page to see the resolve message.
http://plnkr.co/edit/FomhxYIra5GI7nm1KpGb?p=preview
Code:
var resolveTestApp = angular.module('resolveTestApp', ['ngRoute']);
resolveTestApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController',
resolve: {
resolveMessage: function() {
return 'This is the resolve message';
}
}
})
});
resolveTestApp.controller('mainController', function($scope) {
$scope.message = 'Everyone come and see how good I look!';
});
resolveTestApp.controller('aboutController', ['$scope', 'resolveMessage', function($scope, resolveMessage) {
$scope.message = resolveMessage;
}]
);
It may be the version of Angular you're using or a problem when you're minifying your code.

Related

Angularfire ngRoute/resolve issue, jumps to otherwise

I'm using the latest Angular + Firebase and trying to set up a login authorization system. I have home.html which contains login+signup links, going to login.html and adding credentials works just fine (logging correct UID when submittet) but it's supposed to route to dash.html but goes back to home.html.
I've figured out that it seem to be issues with my resolve functions because the problem disappears when I remove .otherwise. But I still want (need?) it there I think.
If I'm logged in (but redirected to home.html) I can still access dash.html through the URL and I cannot access it again if I use the logout function at dash.html and that's how it should be.
But I can't figure out why I'm redirected to home.html in the first place.
Here's some of the code, any help appreciated:
My .run, .config and routes.
app.run(['$rootScope', '$location',
function($rootScope, $location){
$rootScope.$on('$routeChangeError',
function(event, next, previous, error){
if(error === 'AUTH_REQUIRED'){
$location.path('/home');
}
});
}]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider,
$locationProvider){
$routeProvider
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$waitForAuth();
}]
}
})
.when('/dash', {
templateUrl: '/dash.html',
controller: 'dashController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$requireAuth();
}]
}
})
.otherwise({ redirectTo: '/home' });
}]);
My login controller:
app.controller('loginController', ['currentAuth', '$scope', '$firebaseAuth',
'Auth', '$location', '$rootScope',
function(currentAuth, $scope, $firebaseAuth, Auth, $location, $rootScope){
var ref = new Firebase('https://url.firebaseio.com');
$scope.auth = $firebaseAuth(ref);
$scope.loginUser = function(){
$scope.auth = Auth;
$scope.auth.$authWithPassword({
email:$scope.email,
password:$scope.password
}, {
remember: 'sessionOnly'
}).then(function(authData) {
console.log('Logged in as: ', authData.uid);
$scope.auth.$onAuth(function(authData) {
$rootScope.auth = true;
$scope.auth = Auth;
$location.path('/dash.html');
})
}).catch(function(error) {
console.log('There was an error: ', error);
});
};
}]);
And my factory and module:
var app = angular.module('app', ['firebase', 'ngRoute']);
app.factory('Auth', ['$firebaseAuth',
function($firebaseAuth){
var ref = new Firebase('https://url.firebaseio.com');
return $firebaseAuth(ref);
}]);
it has with your resolve issue.
If you look at the documentation firebase doc
you will see that they use the
$waitForSignIn
or
$requireSignIn
functions. I know that because I have done the same thing. Try that instead and it should work

Angularjs routing without hash with multiple var

Yo everyone.
I searched how to remove the hash(#) from the routing (source: AngularJS routing without the hash '#') but I encountered a problem.
I'll explain.
$locationProvider.html5Mode(true);
$routeProvider
.when('/test', {
controller: TestCtrl,
templateUrl: 'test.html'
})
.when ('/test/:idPage', {
controller: PageCtrl,
templateUrl: 'page.html'
})
.otherwise({ redirectTo: '/test' });
For the first redirection
- I've got something like : www.my-website.com/test
all is working fine.
For the second :
- www.my-website.com/test/hello
and here, there is a prob, when I put more than one " / " in the route, no page is loaded and I've got two
Failed to load resource: the server responded with a status of 404
(Not Found)
in my console.
One called : www.my-website.com/test/page.html and the other : www.my-website.com/test/hello
Hope someone can help me. Thanks in advance.
Angular 1.4.x requires that 'ngRoute' be included in the module to use $routeProvider and $locationProvider so include it as a <script...>:
angular-router (see here).
I am assuming you see something like:
To include it in your module:
var app = angular.module('someModule', ['ngRoute']);
And the controller needs to be in quotes controller: 'someCtrl' like:
$locationProvider.html5Mode(true);
$routeProvider
.when('/test', {
controller: 'TestCtrl',
templateUrl: 'test.html'
})
.when ('/test/:idPage', {
controller: 'PageCtrl',
templateUrl: 'page.html'
})
.otherwise({ redirectTo: '/test' });
Here is an example that I put together: http://plnkr.co/edit/wyFNoh?p=preview
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/hello/:idHere', {
templateUrl: 'resolveView.html',
controller: 'helloCtrl',
resolve: {
exclamVal: function(){
return '!!!!!!!!!!'
}
}
})
.when('/default', {
templateUrl: 'default.html',
controller: 'defaultCtrl'
})
.when('/test', {
controller: 'testCtrl',
templateUrl: 'test.html'
})
.otherwise({ redirectTo: '/default' });
$locationProvider.html5Mode(true);
}]);
app.controller('MainCtrl', function($scope, $location, $routeParams) {
});
app.controller('testCtrl', function($scope, $routeParams) {
console.log('hi')
});
app.controller('defaultCtrl', function($scope, $routeParams) {
console.log('Inside defaultCtrl')
});
app.controller('helloCtrl', function($scope, exclamVal, $routeParams) {
$scope.exclamVal = exclamVal;
$scope.myVar = $routeParams.idHere;
});

Parameters routes are not redirects to page 404

I ask them to help solve this problem, follows the code :
Controller
angular.module('tareasApp')
.controller('HumorCtrl', function ($scope, $route, $location) {
$scope.pageName = $route.current.params.pageName;
$scope.items =[
{
href:'/humor/smile-today',
img:'smile.jpg',
descricao:'Those Relaxing Sounds of Waves'
}
];
});
angular.module('tareasApp')
.controller('NewsCtrl', function ($scope, $route, $location) {
$scope.pageName = $route.current.params.pageName;
$scope.items =[
{
href:'/news/news-today',
img:'news.jpg',
descricao:'Those Relaxing Sounds of Waves'
}
];
});
App.js
myApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
title: 'Home Page',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/humor/:pageName', {
templateUrl: 'views/wizard.html',
controller: 'HumorCtrl'
})
.when('/news/:pageName', {
templateUrl: 'views/wizard.html',
controller: 'NewsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
When I type any route that does not exist right after the bar, eg:
domain.com/hhhoedr
returns to the start page .
The problem is in the sub-directory, which contains the $routeParams, typing a page that does not exist , eg:
domain.com/humor/hhhoedr
is not redirecting to index.html or to 404.html.
I would like to adapt this code, I found in another answer, to my app.
myApp.constant('EXISTING_PAGES', [
'page1',
'page2',
...
]);
resolve: {
exists: function ($location, $route) {
if (EXISTING_PAGES.indexOf($route.current.params.page) === -1) {
$location.path('/error/404');
}
return true;
}
}
.when('/error/404', {
templateUrl: '404.html'
})
.otherwise({
redirectTo: '/error/404'
});
how can I do it?
When you are typing any route e.g-domain.com/hhhoedr,It is returning to starting page because check you last part of your code,you are setting it like below.
.otherwise({
redirectTo: '/'
});
If you will set anything except from your all .when part it will simple redirect to the starting page.Try to set it for redirecting to any other page as per your requirement.
Ok,Now you can write it like below.
.otherwise({
redirectTo: '/here give your destination path(e.g-404.html...etc)'
});

"Argument 'BrowseController' is not a function, got undefined" in AngularJS 1.3.8

I was working on my AngularJS application and suddenly I received the error "Argument 'BrowseController' is not a function, got undefined" I undid all my changes and tried the answers supplied on here but the problem still remains.
Here is my app.js file
'use strict';
var app = angular
.module('BikeShopApp', [
'ngAnimate',
'ngResource',
'ngRoute',
'firebase',
'toaster',
'angularMoment'
])
.constant('FURL', 'contains url to my application')
.run(function($rootScope, $location) {
$rootScope.$on("$routeChangeError", function(event, next, previous, error) {
// We can catch the error thrown when the $requireAuth promise is rejected
// and redirect the user back to the login page
if (error === "AUTH_REQUIRED") {
$location.path("/login");
}
});
})
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/browse.html',
controller: 'BrowseController'
})
.when('/browse/:taskId', {
templateUrl: 'views/browse.html',
controller: 'BrowseController'
})
.when('/register', {
templateUrl: 'views/register.html',
controller: 'AuthController'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'AuthController'
})
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
controller: 'DashboardController',
resolve: {
currentAuth: function(Auth) {
return Auth.requireAuth();
}
}
})
.otherwise({
redirectTo: '/'
});
});
and here is the main part of my browse.js controller
'use strict';
app.controller('BrowseController', function($scope, $routeParams, toaster, Task, Auth, Comment, Offer) {
Any help would be greatly appreciated thanks
I've managed to fix this myself, as it turns out at the bottom of my code I was missing a bracket
This is what it as originally
Offer.acceptOffer($scope.selectedTask.$id, offerId, mechanicId.then(function() {
And here is the updated version where I have added the bracket which threw the entire error
Offer.acceptOffer($scope.selectedTask.$id, offerId, mechanicId).then(function() {

Error: $injector:modulerr Module Error, property 'when' of undefined Angular

I have been researching and trying to figure out this error for 2days now and Still no luck.
To begin I new to angular, and I have following this tutorial : http://jphoward.wordpress.com/2013/01/04/end-to-end-web-app-in-under-an-hour/
Every was going well until my grid was not filling with data. So I decided to make minor changes to code and now I have ran into this error.
in my js file:
var MyApp = angular.module("Myapp", ["ngResource", "ngRoute"]).
config([function ($routeProvider) {
$routeProvider.when('/', {templateUrl: 'list.html', controller: 'ListCtrl' }).
otherwise({ redirectTo: '/' });
}]);
MyApp.factory('Myapp', function ($resource) {
return $resource('/Myapp/:id', { id: '#id' }, { update: {
method: 'PUT' } });
});
MyApp.controller('ListCtrl', ['$scope', 'ds72', function ($scope, Myapp) {
$scope.todos = Myapp.query();
}]);
can some one please explain to me what i am doing wrong?
PS: These are all my Scripts
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-resource.min.js"> </script>
<script src="/Scripts/angular-route.min.js"></script>
try something like that
var MyApp = angular.module("Myapp", ["ngResource", "ngRoute"]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {templateUrl: 'list.html', controller: 'ListCtrl' }).
otherwise({ redirectTo: '/' });
}]);
you must add the name of the provider to inject when you use the array declaration
.config(['$routeProvider'/*must be the exact name*/, function(route/*get the $routeProvider value*/) {}])
//equivalent as
.config(function($routeProvider) {})

Categories

Resources