I've started learning Angular JS and I'm having a problem with injecting a service into a controller. I'm trying to put the ThreadFactory service into ThreadController, but I'm getting an undefined error when calling it. Any advice would be great. The error I'm getting is:
Unknown provider: $scopeProvider <- $scope <- ThreadService
app.js
angular.module('threadsApp', ['ngRoute']);
angular.module('threadsApp')
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/index.html',
})
.when('/selected/:topicName', {
templateUrl: 'views/threads.html',
controller: 'ThreadController',
})
.otherwise({
redirectTo: "/"
});
$locationProvider.html5Mode(true);
});
ThreadController.js
angular.module('threadsApp').controller("ThreadController",
["$scope", "$route", "$routeParams", "ThreadService", function ($scope, $route, $routeParams, ThreadService) {
$scope.test = "Hello!";
$scope.test2 = ThreadService.get();
}]);
ThreadService.js
angular.module('threadsApp').service("ThreadService", ["$scope", function ($scope) {
return {
get: function() {
return "Hello";
}
}
}]);
Order of Imports
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="components/app.js"></script>
<script src="components/bodyController.js"></script>
<script src="components/TopicController.js"></script>
<script src="components/ThreadService.js"></script>
<script src="components/ThreadController.js"></script>
You can't actually inject $scope into your ThreadService the way you're trying to. $scope isn't a typical service when you inject it into a controller. If you remove the $scope injection from Threadservice.js, I would bet the error will go away.
In the interest of not being redundant, a fuller explanation can be found here:
Injecting $scope into an angular service function()
Related
I'm trying to create a simple modal that pops up and gives different menu options. It should be easy, and I followed the Plunker for modals on the ui bootstrap website but I'm getting an error:
$uibModal is an unknown provider
Here's the angular code:
angular.module('billingModule', ['ngAnimate', 'ui.bootstrap']);
angular.module('billingModule').controller('StoreBillingCtrl', function ($scope, $uibModal) {
$scope.openStoreBilling = function () {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'storeBillingContent.html',
controller: 'ModalInstanceCtrl',
});
};
});
angular.module('billingModule').controller('OfficeBillingCtrl', function ($scope, $uibModal) {
$scope.openOfficeBilling = function () {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'officeBillingContent.html',
controller: 'ModalInstanceCtrl',
});
};
});
angular.module('billingModule').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance) {
$scope.close = function () {
$uibModalInstance.dismiss();
}
});
I read the error docs and realized that this is a dependency error. But I just don't see where I went wrong. I have angular 1.4.8 and ui-bootstrap 0.14.3.
Here are the scripts that I added:
<head runat="server">
<title>DP Billing</title>
<link href="../CSS/bootstrap.css" rel="stylesheet" />
<link href="../CSS/base.css" rel="stylesheet" />
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-animate.js"></script>
<script src="../Scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script src="../Scripts/billing-modals.js"></script>
</head>
You have to inject the dependency into your controller using the brackets in your controller declaration.
What you have:
angular.module('billingModule').controller('StoreBillingCtrl', function ($scope, $uibModal) { ... });
What you should have:
angular.module('billingModule').controller('StoreBillingCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) { ... }]);
The same applies to the other controllers
A better style:
angular.module('billingModule').controller('StoreBillingCtrl', ['$scope', '$uibModal', StoreBillingCtrlFunc]);
StoreBillingCtrlFunc function ($scope, $uibModal) {
...
}
I would recommend adopting a style as an approach to avoid syntactical errors. John Papa's Angular Style Guide is a good start.
If you use that style it becomes clear what it is that you are declaring and what it is that you are injecting. Not to mention the confusion of having an array where all the elements except for the last one are dependencies, and the last one being the controller itself.
angular.module('billingModule').controller('StoreBillingCtrl', StoreBillingCtrlFunc);
StoreBillingCtrlFunc.$inject = ['$scope', '$uibModal'];
StoreBillingCtrlFunc function($scope, $uibModal){
...
}
I'm trying to create a simple website using angular as front-end.
Is there a way to create partial views and routing without having a webserver?
I've been trying to do so, but I keep getting this error:
Uncaught Error: [$injector:modulerr]
Here's my code: index.html
<!DOCTYPE html>
<html lang="en" ng-app="cerrajero">
<head>
<meta charset="UTF-8">
<title>Cerrajero</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
</head>
<body ng-controller="MainCtrl">
<div ng-view></div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script type="text/ng-template" id="partials/contact.html" src="partials/contact.html"></script>
<script type="text/ng-template" id="partials/services.html" src="partials/services.html"></script>
<script type="text/ng-template" id="partials/home.html" src="partials/home.html"></script>
</body>
</html>
and the app.js:
var app = angular.module('cerrajero', []);
app.config([function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/services', {
template: 'partials/services.html'
}).
when('/contact', {
template: 'partials/contact.html'
}).
when('/home', {
template: 'partials/home.html'
}).
otherwise({
redirectTo: '/home',
template: 'partials/home.html'
});
}]);
function MainCtrl ($scope) {
};
What am I doing wrong?
edit
I've added the ngRoute but I still get the same error when I open the index.html file in the browser.
var app = angular.module('cerrajero', ['ngRoute']);
app.config([function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/services', {
template: 'partials/services.html'
}).
when('/contact', {
template: 'partials/contact.html'
}).
when('/home', {
template: 'partials/home.html'
}).
otherwise({
redirectTo: '/home',
template: 'partials/home.html'
});
}]);
function MainCtrl ($scope) {
};
edit 2
Here's the files on github:
https://github.com/jsantana90/cerrajero
and here's the website when it loads:
http://jsantana90.github.io/cerrajero/
edit 3
I've manage to get rid of the error by having the following code:
var app = angular.module('cerrajero', ['ngRoute']);
app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(false);
$routeProvider.
when('/services', {
template: 'partials/services.html'
}).
when('/contact', {
template: 'partials/contact.html'
}).
when('/home', {
template: 'partials/home.html'
}).
otherwise({
redirectTo: '/home',
template: 'partials/home.html'
});
}]);
app.controller('MainCtrl', function ($scope) {
});
I added this app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
But now my page is blank. It doesn't redirects or anything.
Have I placed everything how it's suppose to go?
edit 4
I forgot to change ui-view to ng-view. Now it works but it's showing in the view: partials/home.html instead of the actual view.
edit 5
Ok so, after having this final code:
var app = angular.module('cerrajero', ['ngRoute']);
app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
$routeProvider.
when('/services', {
templateUrl: './partials/services.html'
}).
when('/contact', {
templateUrl: './partials/contact.html'
}).
when('/home', {
templateUrl: './partials/home.html'
}).
otherwise({
redirectTo: '/home'
});
}]);
app.controller('MainCtrl', function ($scope) {
});
I get this error:
XMLHttpRequest cannot load file:///partials/home.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Now I'm guessing this is because I don't have a webserver running. How do I get it to work without a webserver?
solution
When I uploaded the files to github it seems to work there, but not locally.
Looks like you are using ngRoute and forgot to include it!
First load angular-route.js after loading angular.js. The inject ngRoute as a module:
var app = angular.module('cerrajero', ['ngRoute']);
Try removing the array syntax brackets from inside your config function. I believe there are two different ways of invoking these functions, either with a standalone function or with an array for any minification processes.
You should either one of the following:
app.config(function ($locationProvider, $routeProvider) {
// your code here
});
Or define the variable names with the array syntax for use in minifiers
app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
// your code here
}]);
When you pass in an array to the config function, I believe Angular is expecting the first parameters to be a string value.
You should use ui-router instead of ng-route. It will allow you to nest views. Most current Angular projects use ui-router. ui-router scotch.io
Also, for your controller try app.controller('MainCtrl', function($scope){...});
Replace
var app = angular.module('cerrajero', []);
with
var app = angular.module('cerrajero', ['ngRoute']);
I am building my first angularJS app and I am struggling with getting parameters from my URL into my code.
The URL has a single parameter, subject and all I am trying to do at this stage is display it on the screen...
Javascript:
app.config(function($routeProvider) {
$routeProvider
.when('/setspage/:subject',
{templateUrl: "setspage.html",
controller: "setsController"
}),
});
angular.module("app").controller("setsController", function($scope, $routeParams, $http) {
$scope.selectedSubject = routeParams.subject
});
HTML:
<body ng-controller="setsController">
<div class="page-header">
<h1>Subject : {{selectedSubject}}</h1>
</div>
<script src="./node_modules/angular/angular.js"></script>
<script src="./node_modules/angular-route/angular-route.js"></script>
<script src="scripts/app.js"></script>
</body>
change
routeParams.subject
to
$routeParams.subject
Change your controller like this
angular.module("app").controller("setsController",['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
$scope.selectedSubject = $routeParams.subject
}]);
I am having some issues trying to use the Angular dependency injection with different modules. At the moment, I have the following. In my index.html, the files are loaded in the following order (end of <body> tag):
network.js
authentication.js
login.js
app.js
network.js
angular.module('services.network', [])
.factory('Network', ['$http', '$state', function ($http, $state) { ... }]);
authentication.js
angular.module('services.authentication', ['services.network'])
.factory('Authentication', ['$state', 'Network', function ($state, Network) { ... }]);
login.js
angular.module('controllers.login', [])
.controller('LoginCtrl', ['$scope', function ($scope) { ... }]);
app.js
var app = angular.module('parkmobi', [
'ngRoute',
'services.network',
'services.authentication',
'controllers.login'
]);
app.run(['$rootScope', function ($rootScope) {
$rootScope.$on('$viewContentLoaded', function () {
$(document).foundation('reflow');
});
}])
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
});
}]);
Up until this point, everything seems to be quite happy. Now, however, I want to use the Authentication service in the LoginCtrl, which I would have thought is done as follows:
login.js
angular.module('controllers.login', ['services.authentication'])
.controller('LoginCtrl', ['$scope', 'Authentication', function ($scope, Authentication) { ... }]);
However, this causes the following injection error:
Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=%24stateProvider%20%3C-%20%24state%20%3C-%20Authentication
R/<#http://localhost/testapp/vendor/angularjs/angular.min.js:6:417
Error came because you've injected $state provider in your Authentication factory, without having ui.router module in app.js parkmobi module.
It should use $route instead of $state as your are doing your route in angular-router.
angular.module('services.authentication', ['services.network'])
.factory('Authentication', ['$route', 'Network', function ($route, Network) { ... }]);
Or if you want to use ui-router then you need to use $stateProvider while registering states & ui.router module should be include in your app.
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) {})