Angular - Access config injected dependencies - javascript

When I try to access the $location variable injected into the config from my resolve route, I get a "Unknown Provider" error in the console.
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', '$locationProvider', function ($routeProvider, $location) {
$location.html5Mode(true);
$routeProvider.when('/', {
templateUrl: 'home/home.html',
controller:'homeCtrl',
controllerAs: "vm",
resolve:{
getData: function(){
var param = $location.search().options
}
}
})
Shouldn't the $location parameter be accessible like a closure? I'm fairly new to JS and Angular, so I need clarification.
Thanks!

if you're using the array notation, then the strings must match what you're injecting. in this case, if you want to use $location, you should inject $location, not $locationProvider

Related

routeParams doesnt inject into my controller?

I was looking at some how-tos on doing angular-routing and to pass parameters into a controller. This is what i did:
.controller("myController", ["$scope", "$routeParams", function($scope, $routeParams, Units, Tests){
//Units and Tests are both factories i created to reference within this function.
var id = $routeParams.id;
console.log(id);
}]);
When I did this, it failed to inject "$routeParams" into my application.
I looked at the angular.js file, and it looks like i am running: #license AngularJS v1.5.3
Is this way of doing it no longer the correct way? I tried to update it to:
.controller("myController", ["$scope", "ngRoute", function($scope, ngRoute, Units, Tests){
// ...
}]);
but that seemed to also not inject correctly.
Is there something I am missing?
Currently I am developing with the Ionic Framework, which is leveraging the AngularJS tools.
When dealing with ionic, as stated within the question, you connect to the $stateProvider so when you are creating a state such as:
$stateProvider
.state("unit", {
url: "/unit/:id",
templateUrl: "templates/unit.html",
controller: "UnitController"
})
you would then in your controller do:
.controller("myController", ["$scope",
"$stateParams",
function($scope, $stateParams, Units, Tests){
var id = $stateParams.id;
console.log(id);
}]);
This is the way to do it in Ionic, since it is leveraging a $stateProvider over a $routeProvider
If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module.
The ngRoute module routes your application to different pages without reloading the entire application.
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.html"
})
.when("/red", {
templateUrl : "red.html"
})
.when("/green", {
templateUrl : "green.html"
})
.when("/blue", {
templateUrl : "blue.html"
});
});
Your application needs a container to put the content provided by the routing.
This container is the ng-view directive.
like this
<div ng-view></div>
You can also define controllers for each view
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.html"
})
.when("/london", {
templateUrl : "test.html",
controller : "myController"
})
});

routeParams are Empty

I am trying to get URL parameters using $routeParams:
var myApp = angular.module('myApp', [
'ngRoute',
'appControllers',
'appFilters',
'appServices'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/admin/organisations/:organisation_id', {
controller: 'UpdateOrganisationCtrl'
});
}]);
and in my Controller:
appControllers.controller('UpdateOrganisationCtrl', ['$rootScope', '$scope', '$http', '$window', '$routeParams',
function($rootScope, $scope, $http, $window, $routeParams) {
console.log($routeParams.organisation_id);
}]);
However I am printing undefined as $routeParams is {} Any thoughts?
The url you tried to access should be
localhost:3000/#/admin/organisations/56cde4bf911747ea200d5a63
ngRoute will make your application a Single Page Application, where the relevant part of the url for the router will be after # (beautifully called the hashbang).
Look at the example:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
However, the url you give could work if you use HTML5Mode for $location service of angular.
See those links for more information:
AngularJS routing without the hash '#'
Using $location

Unable to fetch value from angular app.factory

I am trying to share variable among the controller so I am using angular's Factory. I have following code for the same:
var app = angular.module('chartApp', ['ngRoute']);
app.factory('UserVerified', function() {
return {bool: false};
});
app.config(function ($routeProvider) {
$routeProvider
.when('/',{
templateUrl: 'pages/home.html',
controller: 'PredictionController'
})
});
app.controller('PredictionController', ['$scope', '$http', '$interval', function($scope, $http, $interval){
$scope.hasPermission = UserVerified;
}]);
and on HTML i am just using hasPermission.bool to set visibility of a <div>.
But the issue is angularjs is unable to identify UserVerified defined in "app.factory".
I am getting following error:
ReferenceError: UserVerified is not defined
I referred following : Share data between AngularJS controllers
Only difference I can find is, I am using dependencies which is not used in the example in the above link.
you need to inject your custom service in your controller
app.controller('PredictionController', ['$scope', '$http', '$interval','UserVerified',function($scope,$http,$interval,UserVerified) {
$scope. hasPermission = UserVerified.bool; //true
}]);
inorder to avoid breaking of your application after minification of code you can also use $inject in angularjs to inject dependecies.
app.controller("PredictionController",PredictionController);
PredictionController.$inject = [$scope','$http','$interval','UserVerified']//dependencies
function PredictionController($scope,http,interval,UserVerified){
$scope. hasPermission = UserVerified.bool; //true
}
Note: Services names will be renamed after the minification and can indulge in breaking your application
You need to do this,
app.controller('PredictionController', ['$scope', '$http', '$interval', 'UserVerified', function($scope, $http, $interval, UserVerified){
$scope.hasPermission = UserVerified.bool;
}]);
You need to pass the service as a parameter to controller
You need to inject UserVerified into your controller.
app.controller('PredictionController', ['$scope', '$http', '$interval', 'UserVerified', function($scope, $http, $interval, UserVerified){
$scope.hasPermission = UserVerifiedvalue.;
}]);
Plus, in UserVerified you are returning a key which is a reserved word. It will work but will create unnecessary confusion.
app.factory('UserVerified', function() {
return {value: false};
});
Here is a plunker as a demo.

AngularJS TypeError: undefined is not a function on ng-view directive

I'm trying to wire up a simple AngularJS app and I cannot get past a undefined is not a function error on my view directive. The weird thing is that the first view actually loads up and is rendered to the directive but I am unable to navigate to my 2nd view. The controllers definitely aren't running. I'm not sure what's going on here. Any ideas?
Angular version: 1.2.26 (same error with 1.2.20)
Error
App Code
var app = angular.module('myApp', ['ngRoute', 'ngResource']);
app.controller('Home', ['$scope', function ($scope) {
console.log('Home controller hit.');
}]);
app.controller('About', ['$scope', function ($scope) {
console.log('About controller hit.');
}]);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', { templateUrl: 'SiteAssets/views/home.html', controller: 'Home' })
.when('/home', { templateUrl: 'SiteAssets/views/home.html', controller: 'Home' })
.when('/about', { templateUrl: 'SiteAssets/views/about.html', controller: 'About' })
.otherwise({ redirectTo: '/' });
});
You need to inject $document into your controllers like this:
app.controller('About', ['$scope','$document', function ($scope, $document) {
$document.title = 'About Us';
console.log('About controller hit.');
}]);
It might be the $document that is throwing the error, as angular does not know what it is without the injection. However, the error for this issue would be an Error: Unknown provider:
This issue was caused by an error in a script within my Home View. I'm still having an issue with my second view loading up. Thanks to all who helped me on this issue.

AngularJS app URL

I am using ngRoute in my AngularJS app to build up different app routes, below is part of my app.js. Now the problem I am facing is that the URL is shown as ( localhost/myapp/index.html#/home ) while my client needs is at localhost/myapp#/home so I was wondering how I can get the index.html out of the equation or at least make it as localhost/myapp/index#/home without the .html? Thanks
var myApp = angular.module('myApp', ['ngRoute','ngSanitize']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home',
{ templateUrl: 'templates/home.html',
controller: 'homeController'
});
$routeProvider.when('/about',
{templateUrl: 'templates/aboutus.html',
controller: 'aboutUsController'
});
$routeProvider.otherwise({redirectTo: '/home'}); }]);
You should be able to do this with a combination of $locationProvider.html5Mode(true) and <html><head><base href="/myApp">

Categories