Angular module loading error - javascript

I have an angular project that I'm breaking out into a better file structure but I'm getting Argument 'fn' is not a function, got undefined for an error when creating a new service. Any ideas what I'm doing wrong?
app.js
angular.module('app', [
'app.controllers'
]);
angular.module('app.controllers', ['leaflet-directive', 'app.services']);
angular.module('app.services', []);
main.controller.js
angular.module('app.controllers')
.controller('MainCtrl', MainCtrl);
function MainCtrl($scope, $window, leafletData, DataService) {
var main = this;
main.items = DataService.GetItems();
//Other controller stuff
};
data.service.js
angular.module("app.services")
.factory('DataService', DataService);
var DataService = function(){
return data = {
getItems: function(){
return [//data here];
}
};
}

Your declaration of DataService is the problem. You're declaring it after you're using it. You should change your declaration of DataService to function DataService() instead of setting it to a var to take advantage of function hoisting

Related

unable to inject a service in controller

I am using requireJS for my angularjs app.
common.service.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.config(['$provide', function ($provide) {
$provide.factory("CommonService", CommonService);
}]);
CommonService.$inject = ["$http", "$q", "$window"];
function CommonService($http, $q, $window) {
var service = {};
service.sharedValue;
return service;
}
});
page1.controller.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
// Q2: common service
$scope.commonService = CommonService;
}]);
});
Now When I am running my app, it throws me below error:
Error: [$injector:unpr] Unknown provider: CommonServiceProvider <- CommonService <- Page1Controller
any inputs?
Your core module should have empty dependencies injected
var coreModule = angular.module('coreModule',[]);
Also in page1. controller you dont have to declare the module again, you can just use
angular.module('coreModule')
.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
Define config
Define the service
Define the controller, inject the service, use the dependency in function declaration etc. As you would know, both are needed, after all you need the those handles, else what's the point in injecting.
Define a module, define module dependencies. NOTE that the service has to be defined before controller. If you reverse the order, you will get an error, probably that's what is happening here. Without full code, I can't tell.
bootstrap angular.
Finally working plunkr: http://plnkr.co/edit/CE9enkgW3KASx8pf5vdb?p=preview
define('config',[],function(){
function config($routeProvider) {
$routeProvider.when('/home', {templateUrl: 'tpl.home.html', controller: 'HomeController'})
.otherwise({redirectTo: '/home'});
}
config.$inject=['$routeProvider'];
return config;
});
define('dataSvc',[], function(app){
function factoryFunc ($q, $timeout){
var svc = {getData: getData};
return svc;
function getData() {
console.log('executing function');
var d = $q.defer();
$timeout(function(){
console.log("firing timeout");
d.resolve({name:"test", data:[1, 2, 3, 4]});
}, 750);
return d.promise;
}
}
factoryFunc.$inject=['$q', '$timeout'];
return factoryFunc;
});
define('HomeController',[], function() {
function HomeController($scope, dataSvc) {
$scope.name = "Mahesh";
dataSvc.getData().then(function(result){
$scope.data=result;
console.log($scope.data);
});
}
HomeController.$inject=['$scope','dataSvc'];
return HomeController;
});
define('coreModule', ['config', 'dataSvc', 'HomeController']
, function(config, dataSvc, HomeController){
var app = angular.module('app', ['ngRoute','ngResource']);
app.config(config);
app.factory('dataSvc',dataSvc);
app.controller('HomeController', HomeController);
});
require(['coreModule'],
function() {
angular.bootstrap(document, ['app']);
}
);
Refer also,
https://www.sitepoint.com/using-requirejs-angularjs-applications/
http://beletsky.net/2013/11/using-angular-dot-js-with-require-dot-js.html

Using Browserify with Angular JS - - Passing a service into a Controller

As the title suggests I've recently started a new project where I'm using Browserify (and Gulp) to concatenate my Angular JS files (and the Angular sourcefile) into a single file - bundle.js.
I've decided to split my controllers, services and directives into separate files and then "require" them into my app.js file using Browserify like this:
(function () {
'use strict';
require('angular');
var tabCtrl = require('./controllers/tabs'),
dataService = require('./services/');
angular.module("citiToolsApp", [])
.service('dataService', ['$scope', dataService])
.controller('TabController', ['$scope', tabCtrl]);
}());
However when I try to access my service - dataService - from within my Tab Controller like this:
module.exports = function($scope, tabController) {
dataService.getPrograms(function (response) {
console.log(response.data);
});
};
I get an undefined error. I believe I need to pass dataService into the tabController but I'm unsure on the syntax to do this. Can anyone help with this?
Thanks
EDIT
I've also added the contents of my service file for further detail:
module.exports = function($http) {
this.getPrograms = function(callback) {
$http.get('/programs')
.then(callback);
};
};
I've realised my own mistake. I needed to pass in $http rather than $scope. So instead of:
(function () {
'use strict';
require('angular');
var tabCtrl = require('./controllers/tabs'),
dataService = require('./services/');
angular.module("citiToolsApp", [])
.service('dataService', ['$scope', dataService])
.controller('TabController', ['$scope', tabCtrl]);
}());
It should be:
(function () {
'use strict';
require('angular');
var tabCtrl = require('./controllers/tabs'),
dataService = require('./services/');
angular.module("citiToolsApp", [])
.service('dataService', ['$http', dataService])
.controller('TabController', ['$scope', tabCtrl]);
}());

Trouble with Angular Resource Injection

I'm getting started with the meanjs stack, and have reached a bit of a headscratcher that I don't have the understanding to google properly.
I have the following files:
**
(function () {
'use strict';
angular
.module('students')
.controller('StudentsListController', StudentsListController);
StudentsListController.$inject = ['StudentsService'];
function StudentsListController(StudentsService) {
var vm = this;
vm.students = StudentsService.query();
}
}());
Using this service, I am able to get an array of Student objects in the list-students controller, next:
list-students.client.controller.js
(function () {
'use strict';
angular
.module('students')
.factory('StudentsService', StudentsService);
StudentsService.$inject = ['$resource'];
function StudentsService($resource) {
return $resource('api/students/:studentId', {
studentId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
}());
This works as intended.
What I don't understand, is why when I try to use the same service in another controller, it seems to fail to inject, leaving me with an undefined StudentsServices variable.
What gives?
students.client.controller.js
(function () {
'use strict';
// Students controller
angular
.module('students')
.controller('StudentsController', StudentsController);
StudentsController.$inject = ['$scope', '$state', 'Authentication', 'StudentsService'];
function StudentsController ($scope, $state, Authentication, student, StudentsService) {
var vm = this;
vm.authentication = Authentication;
vm.student = student;
vm.students = StudentsService.query();
...
}());
Your inject is wrong.
'$scope', '$state', 'Authentication', 'StudentsService'
But you're telling the controller to expect
$scope, $state, Authentication, student, StudentsService
I figured it out, per
AngularJS: Factory is always undefined when injected in controller
It was that my injections need to be in the same order as the params passed into the controller function.
Aha!

AngularJS : controller with factory

I am new to Angular and I am creating my first app right now. I have a factory in place and my controller should be pulling in data from my source, however I keep on getting this error. My factory is called SpreadsheetFactory.
I have the code for my controller below. Any help is appreciated, thanks!
(function () {
angular
.module('beerApp')
.controller('appController', appController, ['$scope', 'SpreadsheetFactory']);
function appController($scope, SpreadsheetFactory) {
SpreadsheetFactory.getData().then( function (data) {
console.log(data)
});
// $scope.brews = [];
return data;
}
})();
This line is wrong:
.controller('appController', appController, ['$scope', 'SpreadsheetFactory']);
It should be:
.controller('appController', ['$scope', 'SpreadsheetFactory', appController]);

update angular model from a service

angular.module('app.services', []).service("test", function($http, $rootScope){
this.test=function(){
$rootScope.name="test1";
};
};
angular.module('app.controllers', []).controller('TestController', function ($scope, test) {
test.send();
})
I dont get an error but the changes don't get applied to the UI. I tried $scope.apply() and got an error.
We need to tell Angular which modules your module depends on, In our case the main module is app.controllers.
To call service from different model we need tell to controller where is our service:
['app.services']
JS
var appServices = angular.module('app.services', []);
var appCtrl = angular.module('app.controllers', ['app.services']);
appServices
.service("test", function ($http, $rootScope) {
this.send = function () {
$rootScope.name = "test1";
};
});
appCtrl.controller('TestController', function ($scope, test) {
test.send();
});
Demo Fiddle
I think you should change ".service" by ".factory".
As I can see in the creating services docs there are 3 ways of creating custom services. One of then is using factory way, as the following:
var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
Hope to help.

Categories

Resources