im fairly new to angular. im trying to understand why this doesnt work:
error recieved is:
Uncaught Error: [$injector:modulerr] Failed to instantiate module phonecatApp due to:
Error: [$injector:modulerr] Failed to instantiate module phoneList due to:
TypeError: Cannot read property 'controller' of undefined
angular.
module('phoneList').
component(name, component);
var name = 'phoneList';
var component = {
templateUrl: 'phone-list/phone-list.template.html',
controller: ['$http', function PhoneListController($http) {
var self = this;
self.orderProp = 'age';
$http.get('phones/phones.json').then(function(response) {
self.phones = response.data;
});
}]
};
how can i fix this ?
i know i can do this but i prefer decomposing the object as above. please advise
angular.
module('phoneList').
component('phoneList', {
templateUrl: 'phone-list/phone-list.template.html',
controller: ['$http', function PhoneListController($http) {
var self = this;
self.orderProp = 'age';
$http.get('phones/phones.json').then(function(response) {
self.phones = response.data;
});
}]
});
Have you tried to define the name and component vars before using them in .component(name, component) ? Like:
var name = 'phoneList';
var component = {
templateUrl: 'phone-list/phone-list.template.html',
controller: ['$http', function PhoneListController($http) {
var self = this;
self.orderProp = 'age';
$http.get('phones/phones.json').then(function(response) {
self.phones = response.data;
});
}]
};
angular.
module('phoneList').
component(name, component);
this is the index.html. i already have app.module.js defining this
'use strict';
// Define the `phonecatApp` module
angular.module('phonecatApp', [
'ngRoute',
'phoneDetail',
'phoneList'
]);
<!doctype html>
<html lang="en" ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<title>Google Phone Gallery</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="app.css" />
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.module.js"></script>
<script src="app.config.js"></script>
<script src="phone-list/phone-list.module.js"></script>
<script src="phone-list/phone-list.component.js"></script>
<script src="phone-detail/phone-detail.module.js"></script>
<script src="phone-detail/phone-detail.component.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
this is not the issue. my example is straight from the angularjs tutorial with the above only difference of separating the component object from the component itself.
Related
This is in app.js:
var angular = angular.module('ngApp', ['ngRoute']);
angular.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '../templates/companies.html',
controller: 'companies'
})
.........
});
This is in companies.js:
angular.module('ngApp').controller('companies', ['$scope', function($scope) {
.........
}]);
This is in index.html:
<head>
<title>Basic demo</title>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/Controllers/companies.js" type="text/javascript" ></script>
</head>
I keep getting this error:
Uncaught TypeError: angular.module is not a function
at companies.js:1
What am I doing wrong?
You are trying to use a variable called angular. Think what causes that variable to exist. That is found in the angular.js script which must then be included first.
At the time your angular code runs, angular does not exist yet. This is an error (see your console window of Dev Tools ). Kindly use same version of Angular file and angular-route !
Your problem is that you've overwritten angular object in app.js file:
var angular = angular.module('ngApp', ...
Try renaming angular variable to something else, like app.
Here is a plunker example of it:
http://plnkr.co/edit/t9KoqROnfWda8XsThOPE
Use same version of Angular and AngularRoute
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
(function () {
'use strict';
var myApp = angular.module('ngApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
//....
})
})();
<!DOCTYPE html>
<html>
<head>
<title>Angullr</title>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="newController">
{{hello}}
<div my-direcitve></div>
</div>
</div>
</body>
<script type="text/javascript">
(function() {
dir = angular.module('mydirective',[]);
dir.directive('myDirecitve', function() {
return {
template: '<ul><li>No Hello</li></ul>'
};
});
});
var app = angular.module('myApp',['mydirective']);
app.controller('newController',function($scope,myDirecitve){
$scope.hello = 'hello Wolrd';
});
</script>
</html>
Failed to instantiate module myApp due to:
Error: [$injector:modulerr] http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=m...)
at Error (native)
Your directive should use the same Module, change from 'mydirective' to 'myApp'
(function() {
dir = angular.module('myApp');
dir.directive('myDirecitve', function() {
return {
template: '<ul><li>No Hello</li></ul>'
};
});
});
Your code totally mismatched, Why you have used multiple module? And where you call the 'mydirective' module in tour HTMl? and what is the use of this?
Your code should looks like this
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.directive('myDirecitve', function() {
return {
template: '<ul><li>No Hello</li></ul>'
};
});
app.controller('newController',function($scope,myDirecitve){
$scope.hello = 'hello Wolrd';
});
</script>
First, you don't need to add directive to your controller
Seconds, there are 2 ways you can try:
1 use directive as a module:
<script type="text/javascript">
var dir = angular.module('mydirective',[]);
dir.directive('myDirective', function() {
return {
template: '<ul><li>No Hello</li></ul>'
};
});
var app = angular.module('myApp',['mydirective']);
app.controller('newController',['$scope',function($scope){
$scope.hello = 'hello World';
}]);
</script>
2 use in your myApp module:
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.controller('newController',['$scope',function($scope){
$scope.hello = 'hello World';
}]);
app.directive('myDirective', function() {
return {
template: '<ul><li>No Hello</li></ul>'
};
});
</script>
I tested and it works, Hope this help!
I just followed a tutorial about angular on youtube but i'm not able to execute the code due to an routeProvider problem. I tried to include the good link for angular-route.js but it's still doesn't work...
I show you the code:
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<title>Tuto Angular</title>
</head>
<body>
<div>
<div ng-view=""></div>
</div>
<script src="angular.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.js"></script>
<script type="text/javascript">
var demoApp = angular.module('demoApp', ['ng-route']);
demoApp.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'SimpleController',
templateUrl: 'Partials/View1.html'
})
.when('/view2',{
controller: 'SimpleController',
templateUrl: 'Partials/View2.html'
})
.otherwise({ redirectTo: '/' });
});
demoApp.controller('SimpleController', function ($scope){
$scope.customers = [
{name:'John Smith', city:'Phoenix'},
{name:'John Doe', city:'New York'},
{name:'Jane Doe', city:'Chicago'}
];
$scope.addCustomer = function (){
$scope.customers.push(
{
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
};
});
</script>
</body>
When i look into the console it returns me that:
Uncaught Error: [$injector:modulerr]
If you have any idea you're welcome !
change:
var demoApp = angular.module('demoApp', ['ng-route']);
to
var demoApp = angular.module('demoApp', ['ngRoute']);
When injecting a dependency into our app module,use camelCase and not snake-case
Here, use ngRoute and not ng-route
See: https://stackoverflow.com/a/11934258/1177295
In Angular we need to use camelCase for Dependency injection and Directive definition in java Scripts files and snake-case in the HTML pages where directive is used
Lets take if you have directive myFirstDirective in Directive defination you will use
demoApp.directive(myFirstDirective, function () {
return{}
});
In the HTMl you will use
<my-first-directive></my-first-directive>
You have only included it inside the function. You have to inject the serivce into the config method and make sure the ng-route is included in the app references
I'm new on AngularJs.
I have trouble injecting a service into a controller in AngularJS.
I read many tutorials and topics on stackoverflow, but I can't fix my issues because the controller & service use the same module like this:
var myModule = angular.module("myModule", []);
myModule.service("myService", MyService);
myModule.controller("MyController", function($scope, myService) {
myService.doIt();
});
My project works when the service & controller use the same module, but I want each one to use its own module because many controllers should use this service.
(I try to minimize the code)
index.html :
<!doctype html>
<html lang="en" ng-app="interfaceApp">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<head>
<meta charset="utf-8">
<title>Interface de consulation</title>
<link rel="stylesheet" href="resources/css/bootstrap.css">
<link rel="stylesheet" href="resources/css/app.css">
<link rel="stylesheet" href="resources/css/animations.css">
<script src="resources/vendors/jquery/jquery.js"></script>
<script src="resources/vendors/angular/angular.min.js"></script>
<script src="resources/vendors/angular/angular-animate.js"></script>
<script src="resources/vendors/angular/angular-route.js"></script>
<script src="resources/vendors/angular/angular-resource.js"></script>
<!--personal script-->
<script src="js/controllers/router.js"></script>
<script src="js/animations/animations.js"></script>
<script src="js/filters/filters.js"></script>
<script src="js/services/services.js"></script>
<script src="js/services/deserializer.js"></script>
<script src="js/directives/directives.js"></script>
<!-- load my controller -->
<script src="js/controllers/phoneController.js"></script>
<script src="js/controllers/specimenController.js"></script>
<script src="js/controllers/localisationController.js"></script>
</head>
<body>
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div class="view-container">
<div ng-view class="view-frame"></div>
</div>
</body>
</html>
router.js:
'use strict';
/* App Module */
var interfaceApp = angular.module('interfaceApp', [
'ngRoute',
'phoneModules',
'localisationModules',
'specimenModules',
'interfaceFilters',
'interfaceDirectives',
'interfaceAnimations',
'interfaceServices',
// 'DeserializerService' // Error: [$injector:modulerr]
]);
interfaceApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'MainCtrl'
}).
when('/specimens', {
templateUrl: 'partials/specimen/list.html',
controller: 'specimenListeCtrl'
}).
when('/specimens/:specimensId', {
templateUrl: 'partials/specimen/detail.html',
controller: 'specimenDetailCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
js/controllers/specimenController.js :
'use strict';
/* Controllers */
var specimenModules = angular.module('specimenModules', ['ngRoute']);
...
var referencedTag={"mediasSet":"#mediasSet","determinations":"#determinationID"};
specimenModules.controller('specimenListeCtrl', ['$scope', '$http', 'DeserializerService',
function ($scope,$http,DeserializerService) {
var request = 'http://localhost:8888/ui/specimens?limit=10&r_medias=false&orderby=d_determinationid';
$http.get(request).success(function(data) {
DeserializerService.startDeserializer(data,referencedTag);
$scope.specimens=data;
});
}
]);
js/services/deserializer.js :
var deserializerModule = angular.module('DeserializerModule', []);
deserializerModule.service('DeserializerService', function() {
***//specimenModules.service('deserializerService', function() { // work but i dont want to use specimenModules her***
this.referencedTag= [];
this.startDeserializer= function(data,refTag) {
this.referencedTag=refTag;
this.deserializer(data);
}
this.deserializer= function(data) {
...
}
});
I tried many combinations, but all failed giving error like :
Error: [$injector:modulerr]
Error: [$injector:unpr]
but i don't see where it come from on firebug ( the error dont give a line or file )
ERROR:
Error: [$injector:unpr] http://errors.angularjs.org/1.2.17/$injector/unpr?p0=DeserializerServiceProvider%20%3C-%20DeserializerService
u/<#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:6:443
ec/l.$injector<#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:36:139
c#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:34:195
ec/p.$injector<#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:36:209
c#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:34:195
d#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:34:409
f/<.instantiate#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:35:101
Od/this.$get</<#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:66:463
ngViewFillContentFactory/<.link#http://localhost/rec-interface/resources/vendors/angular/angular-route.js:913:1
N#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:54:85
g#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:47:55
v/<#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:46:253
O/<#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:47:485
x#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:51:245
update#http://localhost/rec-interface/resources/vendors/angular/angular-route.js:871:1
Yd/this.$get</h.prototype.$broadcast#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:113:355
updateRoute/<#http://localhost/rec-interface/resources/vendors/angular/angular-route.js:552:15
ze/e/l.promise.then/D#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:99:243
ze/e/l.promise.then/D#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:99:243
ze/f/<.then/<#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:100:407
Yd/this.$get</h.prototype.$eval#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:111:110
Yd/this.$get</h.prototype.$digest#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:108:180
Yd/this.$get</h.prototype.$apply#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:111:449
g#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:72:113
x#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:76:463
ve/</v.onreadystatechange#http://localhost/rec-interface/resources/vendors/angular/angular.min.js:78:1
<div ng-view="" class="view-frame ng-scope">
Thanks for your help, any advice or critics are welcomed.
many thank #jcubic you are right it work !!!
it need double "injection", one for module and one for service name:
var specimenModules = angular.module('specimenModules', ['ngRoute','DeserializerModule']);
...
specimenModules.controller('specimenListeCtrl', ['$scope', '$http', 'DeserializerService', function ($scope,$http,DeserializerService) { ... }])
thanks
I'm trying to make some basic tests on directives on an e2e scenario. The code works just fine
and I can render the new element to the browser. Here the code I'm using.
Here the directive code.
'use strict';
var directives = angular.module('lelylan.directives', [])
directives.directive('device', ['Device', function(Device) {
var definition = {
restrict: 'E',
replace: true,
templateUrl: 'js/templates/device.html',
scope: { id: '#' }
};
definition.link = function postLink(scope, element, attrs) {
scope.$watch('id', function(value){
var device = Device.get({ id: scope.id }, function() {
scope.device = device;
});
});
};
return definition
}]);
Here the Device service code.
// Service Device
'use strict';
angular.module('lelylan.services', ['ngResource']).
factory('Device', ['$resource', '$http', function($resource, $http) {
var token = 'df39d56eaa83cf94ef546cebdfb31241327e62f8712ddc4fad0297e8de746f62';
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token;
var resource = $resource(
'http://localhost:port/devices/:id',
{ port: ':3001', id: '#id' },
{ update: { method: 'PUT' } }
);
return resource;
}]);
Here the app code.
'use strict';
angular.module('lelylan', ['lelylan.services', 'lelylan.directives'])
And here the index.html.
<!doctype html>
<html lang="en" ng-app="lelylan">
<head>
<meta charset="utf-8">
<title>Lelylan Components</title>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<device id="50c61ff1d033a9b610000001"></device>
<!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script> -->
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
After reading the Angular documentation and trying different solutions I came up with the following
test where I try mock my Backend requests. The problem is that the request still hits the real service. It
looks like I'm not able to intercept the requests.
// e2e test
'use strict';
describe('directives', function() {
var resource = { id: '1', uri: 'http://localhost:3001/devices/1' };
var myAppDev = angular.module('myAppDev', ['lelylan', 'ngMockE2E']);
myAppDev.run(function($httpBackend) {
$httpBackend.when('GET', 'http://localhost:3001/devices/1').respond(resource);
$httpBackend.when('GET', /\/templates\//).passThrough();
});
beforeEach(function() {
browser().navigateTo('../../app/index.html');
});
describe('when renders a device', function() {
it('renders the title', function() {
expect(element('.device .name').text()).toEqual('Closet dimmer');
});
it('renders the last time update', function() {
expect(element('.device .updated-at').text()).toEqual('2012-12-20T18:40:19Z');
})
});
});
I think I'm missing some configurations, but I can't really understand which ones.
Thanks a lot.
Reading the the last comment in this question I came with the final solution.
Actually I was missing one important step, due to the fact that I had to use an HTML file that uses the mocked application. Let's make the code speak.
1) I've created an HTML file with the test environment. The main difference is related to the fact that I've set the ng-app=test and I've added two new JS files. The first is /test/e2e/app-test.js and is where I've created the test module and the second is /test/lib/angular-mocks.js.
<!doctype html>
<html lang="en" ng-app="test">
<head>
<meta charset="utf-8">
<title>Lelylan Test</title>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<device id="1"></device>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/settings.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<!-- Test application with mocked requests -->
<script src="../test/e2e/app-test.js"></script>
<script src="../test/lib/angular/angular-mocks.js"></script>
</body>
</html>
Now, lets see how we implement the test module. In here I define a module that is exactly as my main module (lelylan), with the addition of ngMockE2E that lets you access to $httpBackend and mock the HTTP requests.
'use strict';
var resource = { id: '1', uri: 'http://localhost:3001/devices/1' };
var test = angular.module('test', ['lelylan', 'ngMockE2E']);
test.run(function($httpBackend) {
$httpBackend.when('GET', 'http://localhost:3001/devices/1').respond(resource);
$httpBackend.when('GET', /\/templates\//).passThrough();
});
Nothing more. Run scripts/e2e-test.sh and you're done.