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
Related
I tried to use angular cookies in custom service, but got the error:
Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService
I store module, controllers and services in separate files.
Controller:
(function() {
'use strict';
angular
.module('app')
.controller('AuthController', AuthController);
AuthController.$inject = ['$scope', '$http', '$location', 'checkLoginService'];
function AuthController($scope, $http, $location, checkLoginService) {
/* jshint validthis:true */
var vm = this;
vm.title = 'AuthController';
$scope.login = function(user) {
/*logic*/
}
$scope.checklogin = function () {
if (checkLoginService.checkLogin()) {
/*logic*/
}
}
$scope.checklogin();
}
})();
Service:
(function () {
'use strict';
angular
.module('app')
.service('checkLoginService', ['ngCookies', checkLoginService]);
checkLoginService.$inject = ['$http'];
function checkLoginService($http, $cookies) {
return {
checkLogin: function () {
/*logic*/
}
}
}
})();
ngCookies is module not a dependency name, you should inject ngCookies in module dependency and use $cookies to get cookie object
//somewhere in app.js
angular.module('app', ['otherModules', ..... , 'ngCookies'])
Also add $cookies missing dependency inside a checkLoginService $inject array.
angular.module('app')
.service('checkLoginService', ['$cookies', checkLoginService]);
checkLoginService.$inject = ['$http', '$cookies'];
function checkLoginService($http, $cookies) {
return {
checkLogin: function () {
/*logic*/
}
}
}
I have a basic angular setup. I want to add another factory service so that the mainCtrl can use it.
Here is my controller.js
angular.module('Manalator.controllers', [])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Here is my services.js
angular.module('Manalator.services', [])
.factory('cordovaReady', [function () {
return function (fn) {
var queue = [],
impl = function () {
queue.push([].slice.call(arguments));
};
document.addEventListener('deviceready', function () {
queue.forEach(function (args) {
fn.apply(this, args);
});
impl = fn;
}, false);
return function () {
return impl.apply(this, arguments);
};
};
}])
.factory('manaFactory', [function(){
this.testString = function(){
return 'This works';
};
}]);
Here is my routes.js
angular.module('Manalator', ['ngRoute', 'Manalator.services', 'Manalator.controllers'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/main.html'
})
.when('/devotion', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/devotion.html'
})
.when('/results', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/results.html'
})
.otherwise({redirectTo: '/'});
});
I get the following error:
TypeError: Cannot read property 'testy' of undefined
at new <anonymous> (controllers.js:3)
at Object.i [as invoke] (main.min.js:1)
at $get.f.instance (main.min.js:2)
at m (main.min.js:1)
at s (main.min.js:1)
at $get.e (main.min.js:1)
at main.min.js:1
at p.$get.p.$eval (main.min.js:3)
at p.$get.p.$apply (main.min.js:3)
at main.min.js:1
It is a cordova phonegap setup with basic routes. I am new to angular. I have looked over the internet and im having trouble setting up a basic service to hold all my data so i can access it from all my routes. Any help would be appreciated.
You will need to identify your services as a dependency of the controller.
The first step is to make sure you define the services before the controller.
then change the controller code so that it names the services as a dependency.
angular.module('Manalator.controllers', ['Manalator.services'])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Hope this helps!
I need help, about added jasmine tast to my factory.
My code is...
---dataService.js---
angular.module('angularAppApp')
.factory('dataService', function($resource){
return $resource(`http://...:3100/posts/:id`, null,
{
'update': { method:'PUT' }
});
})
---onePostCtrl.js ---
angular.module('angularAppApp')
.controller('onePostCtrl', ['$scope', '$http', '$routeParams', 'dataService',
function ($scope, $http, $routeParams, dataService) {
dataService.get ({id: $routeParams.postId}).$promise.then(function(data){
$scope.postInfo = data;
});
}]);
-- main container ---
angular.module('angularAppApp').controller('postCtrl', ['$scope','$http', 'ngDialog', 'dataService','trimService', function ($scope, $http, ngDialog, dataService, trimService) {
//save data to remote server from loaded pop-up
$scope.savePost = function(){
$scope.addFormData.date = $scope.formated_date;
dataService.save($scope.addFormData, function() {
laodData();
});
ngDialog.closeAll();
};
//delete post from remote server
$scope.deletePost = function(article) {
dataService.delete({ id: article._id }, function() {
laodData();
});
};
//edit post from remote server
$scope.updatePost = function (article) {
dataService.update({ id: article._id},article).$promise.then(function() {
laodData();
});
ngDialog.closeAll();
}
}]);
--- mock data ---
angular.module('mock', []).value('items', [{ ... }]
---At index.html I am have loaded mocks scripts---
src="bower_components/angular-mocks/angular-mocks.js"
src="mosk_data/mocks.module.js"
--Jasmine tests is ...
describe("factory of dataService", function (){
var $httpBackend, $http, $q, factory;
beforeEach(module("angularAppApp"));
beforeEach(module('mock'));
beforeEach(function(){
inject(function($injector, _$httpBackend_,_$http_,_$q_){
$q = _$q_;
$http = _$http_;
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', '/items').respond(items);
factory = $injector.get('dataService');
});
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("Data service", function(){
});
});
Now, I have error "ReferenceError: items is not defined" and cannot ideas how I can test my dataService.
You forgot to inject your value and assign it to a variable in the tests. Try this:
var $httpBackend, $http, $q, factory, items; //declare variable items here (or you can do it inside beforeEach)
beforeEach(module("angularAppApp"));
beforeEach(module('mock'));
beforeEach(function(){
inject(function($injector, _$httpBackend_,_$http_,_$q_, _items_){
$q = _$q_;
$http = _$http_;
//inject the value and assign to your variable
items = _items_
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', '/items').respond(items);
factory = $injector.get('dataService');
});
The Reference error you got was because there was no variable called items. You defined an angular value with name items, but it's not the same as a variable - think of it as it lives "somewhere inside angular guts" and to use it you have to inject it and then use as normal variable.
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.
I am aware that the error which is in the title of this question is basically because in my controller I am injecting a Session service in my controller that has not been defined. I am currently looking at: Angular Devise for which I am rolling out in an application that is using rails but have angular and rails separate. My setup on the angular side is as followed:
main.js
angular.module('App.controllers', []);
angular.module('App.config', []);
angular.module('App.directives', [])
angular.module('App.resources', ['ngResource']);
angular.module('App.services', []);
var App = angular.module("App", [
"ngResource",
"ngCookies",
"$strap.directives",
"App.services",
"App.directives",
"App.resources",
"App.controllers",
"TotemApp.config"
], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "/login";
return;
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
});
Session.js
App.service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = function() {
return $cookieStore.get('_angular_devise_user');
}
this.signedIn = function() {
return !!this.currentUser();
}
this.signedOut = function() {
return !this.signedIn();
}
this.userSession = new UserSession( { email:"sample#email.com", password:"password", remember_me:true } );
this.userRegistration = new UserRegistration( { email:"sample#email.com", password:"password", password_confirmation:"password" } );
}]);
sessions_controller
App.controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save().success(function(data, status, headers, config) {
$cookieStore.put('_angular_devise_user', Session.userSession.email);
$location.path('/todos');
});
}
};
$scope.destroy = function() {
$cookieStore.remove('_angular_devise_user');
$scope.session.$destroy();
};
}]);
routes.js
'use strict';
App.config(function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/sessions/new.html',
controller: 'SessionsController'
})
.when('/sign_up', {
templateUrl: 'views/registrations/new.html',
controller: 'RegistrationsController'
})
.otherwise({
redirectTo: '/'
});
});
This error occurs when I try to access the login page or register page. If someone can shed some light that would be greatly appreciated. Not entirely sure how to resolve this Error: Unknown provider: $SessionProvider <- $Session error
At first glance this looks correct. I can only assume that perhaps you've not included Session.js in your index.html file?
Angular clearly doesn't know what 'Session' service is so there's something wrong there either file not loaded, not loaded correctly or something along those lines as far as I can see.
Edit: Does the error say 'SessionProvider <- Session' or '$SessionProvider -< $session' because if it's the latter, then something is named wrong somewhere in your app since your service is named 'Session' not '$Session'.
When you have syntax error in other javascript or typescript files. You will get the same error. Please make sure that you have no syntax error.