I have a simple question about the dependency injection in Angular. I create custom services in order to use them within each other. Unfortunately I receive errors the way I was trying it. This is my Code:
var myApp = angular.module('app', []);
myApp.service('$service1', ['$rootScope', function($rootScope) {
this.test = function() {
console.log('service1');
};
}]);
myApp.provider('$service2', ['$service1', function($service1) {
var service = 'service2';
this.registerService = function(mytext) {
service = mytext;
};
this.$get = function() {
var that = {};
that.test = function() {
console.log(service);
};
return that;
};
}]);
myApp.config(['$service2Provider', function($service2Provider) {
$service2Provider.registerService('changed service2');
}]);
myApp.controller('AppCtrl', ['$rootScope', '$service1', '$service2',
function($rootScope, $service1, $service2) {
$service1.test();
$service2.test();
}]);
Error: [$injector:modulerr] Failed to instantiate module app due to:
[$injector:unpr] Unknown provider: $service1
http://errors.angularjs.org/1.2.0-rc.2/$injector/unpr?p0=%24service1
If you remove the dependency of $servic1 in $service2 it will work, but why?
The code is mostly right, except you have to inject service dependencies in $get, not in the provider constructor function, like this:
myApp.provider('$service2', function() {
var service = 'service2';
this.registerService = function(mytext) {
service = mytext;
};
this.$get = ['$service1', function($service1) {
var that = {};
that.test = function() {
console.log(service);
};
return that;
}];
});
It appears that provider can not inject such a dependency. If you rewrite $service2 using a factory, it works:
myApp.factory('$service2', ['$service1', function($service1) {
var that = {};
that.test = function() {
$service1.test();
console.log('service2');
};
return that;
}]);
See this plunker: http://plnkr.co/edit/JXViJq?p=preview
Also I believe that service names starting with a $ a reserved for AngularJS and its extensions. Use names without the $ at the beginning for services defined by your application.
Related
I wrote a factory function for some restrict options for all the name fields and I want to use/call that factory globally throughout the application. How can I use the factory globally?
This is my code:
checks.factory('pasteOptions',function($event) {
var clipboarddata = window.event.clipboardData.getData('text');
var regex = new RegExp("^[a-zA-Z.]+$");
var pastedData = window.event.clipboardData.getData('text/plain')
if(pastedData.match(regex) === null) {
event.preventDefault();
return false;
}
});
If you are in fact trying to extend functionality for an HTML tag, you might want to use a directive instead.
To use a factory throughout an application though, it can be done by creating a module for a factory as such:
"use strict";
(function () {
angular.module('example.module.with.factory', [
])
.factory('pasteOptions',function($event) {
var clipboarddata = window.event.clipboardData.getData('text');
var regex = new RegExp("^[a-zA-Z.]+$");
var pastedData = window.event.clipboardData.getData('text/plain')
if(pastedData.match(regex) === null) {
event.preventDefault();
return false;
}
});
})();
and to include this factory into controllers throughout the application, declare it as a parameter in the controllers you wish to use it as such:
"use strict";
(function () {
angular.module("other.module", [
"example.module.with.factory", // Name of the module with the factory
"ui.router"
])
// Include the name of your factory as a parameter to the controller
.controller("otherModule.ctrl", ["$scope", "pasteOptions",
function($scope, pasteOptions) {
// do stuff with your factory
}]);
})();
I have created and injected the service(myService) into my app (app) , but it is not working. The error implies that I have not defined the service anywhere:
Error: [$injector:unpr] Unknown provider: myServiceProvider <- myService <- myController
myService calls another service - ajaxService to do the actual http call.
The only reason I would think that myService throws the above error when trying to call it in myController is because I have another module defined in the app definition (common.components). This module has its own separate services which I am using elsewhere in my app. I am wondering if the app is searching for a definition of myService within that the common.components module instead of inside itself.
Here is my code:
- app.js
var app = angular.module('app ', ['ngRoute','common.components']);
- myService.js
var serviceId = 'myService';
angular.module('app').service(serviceId,['$q','ajaxService','$log',myService]);
function myService($q, ajaxService, $log){
var states = [];
this.getStates = function() {
var defered = $q.defer();
ajaxService.getStates().then(function(result){
states = result.data;
defered.resolve(states);
},
function(error){
deferred.reject();
});
return defered.promise;
};
}
- ajaxService.js
var serviceId = 'ajaxService';
angular.module('app',[]).service(serviceId,['$http','$log',ajaxService]);
function ajaxService($http,$log){
this.getStates = function() {
return $http.get('./json/DATA.json');
};
}
myController.js
(function(){
'use strict';
angular.module('app').controller('myController',['$scope','$log','myService',myController]);
function myController($scope,$log,myService){
$scope.states = [];
myService.getStates().then(function(states){
$scope.states = states;
});
}
})();
I have been trying to find out what is wrong for hours, but I am lost. Can someone help me with this?
I have updated my answer as you have now provided more info.
Your issue is in your ajaxService.js
Change this line
angular.module('app',[]).service(serviceId,['$http','$log',ajaxService]);
to this
angular.module('app').service(serviceId,['$http','$log',ajaxService]);
Your are recreating the app module by adding the [].
I've got this in app.js:
angular.module('App',[]).config(['TranslationProvider', function (TranslationProvider) {
//codes...
}]);
And this service in another file:
angular.module('App')
.provider('Translation', function() {
var translations = {foo:"bar"}
this.$get = function(){
return translations;
};
});
No 404 error with the service js file, but when angular injector try to instantiate it gives me this error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module App due to:
Error: [$injector:unpr] Unknown provider: TranslationProvider
I've followed the angjs documentation https://docs.angularjs.org/guide/providers
It seems to be a bug in Angular 1.2.x. The order of the calls matter. When you call provide before config it works. It also works with Angular 1.3.x regardless of the order.
You are almost there.
First the config:
angular.module('App')
.config(["TranslationProvider", function(theProvider) {
console.log("in config" + theProvider)
theProvider.setName("some name");
}]);
The error you were having was due to you using the constructor function as an argument.
Now your provider:
angular.module('App')
.provider('Translation', function TranslationProvider() {
var translations = {foo:"bar", name:""};
var dynamicName;
this.setName = function(configName) {
dynamicName = configName;
};
this.$get = function(){
translations.name = dynamicName;
return translations;
};
});
Also note that an anonymous function (i.e. .provider('Translation', function () {) could also have been used and the code would have worked just as well.
Using it all in a controller:
angular.module('App')
.controller('MyController', [
'$scope',
'Translation',
function ($scope,
translationProvider) {
$scope.modal = {};
$scope.projects = [];
console.log(translationProvider)
$scope.foo = translationProvider;
}]);
I am building an app using AngularJs.
I have a function (createStarMarkup) that returns a bunch of HTML based on a number.
function(rating) {
var rating = Number(rating);
var markup = "";
//Do some stuff
return markup;
}
I would like to be able to use this function multiple places in my application, so I defined it as a service in a Utility module.
var app = angular.module('utilities', []);
app.factory('createStarMarkup', function(rating) {
var rating = Number(rating);
var markup = "";
// Do some stuff
return markup;
});
I then add the 'utilities' module as a dependency to one of my other modules, and inject the service into the controller.
var app = angular.module('reviews', ['ionic', 'utilities']);
app.controller('reviewController',
['$scope', '$ionicActionSheet', 'createStarMarkup', function($scope, $ionicActionSheet, createStarMarkup){...});
This produces the following error
Error: [$injector:unpr] Unknown provider: $ratingProvider <- $rating <- createStarMarkup
The error goes away if I remove the rating parameter in the createStarMarkup function. Am I on the right track with using factory or should I look into something else?
Your factory definition is not valid. please change it as follows
app.factory('createStartupServices', ['', function() {
return {
getMarkup: function(rating) {
var rating = Number(rating);
var markup = "";
// Do some stuff
return markup;
},
}
}
]);
And your controller, you need to get the method getMarkup as follows
var app = angular.module('reviews', ['ionic', 'utilities']);
app.controller('reviewController',['$scope', '$ionicActionSheet', 'createStartupServices', function($scope, $ionicActionSheet, createStartupServices){
//createStartupServices.getMarkup(123);
});
The problem is here:
app.factory('createStarMarkup', function(rating) {
You are trying to inject a service called rating, that doesn't exist.
What are you trying to to is this:
app.factory('createStarMarkup', function() {
Service = {};
Service.myFunction = function(rating) {
var rating = Number(rating);
var markup = "";
// Do some stuff
return markup;
}
return Service;
});
In this way you can inject the createStarMarkup in any controller/directive/service and use the function like:
createStarMarkup.myFunction(rating);
I have a code of
var viewerAngular = angular.module('ngAppDemo', ['restangular','btford.socket-io'])
.config(function(RestangularProvider) {
$.get('../config/config.xml',
function(data) {
$(data).find('contentserver').each(function() {
serverDetails.contentserver = assignServerDetails($(this));
var restprovider = RestangularProvider;
restprovider.setBaseUrl("http://"+serverDetails.contentserver.ip+":"+serverDetails.contentserver.port+"\:"+serverDetails.contentserver.port);
//$scope.init();
});
});
I need to invoke function init(), after reading the config(../config/config.xml) file.
I got an error of ReferenceError: $scope is not defined.
How can I add $scope in module.config? Or How can I call function from config?
If you need to add something to every scope in config, you can use $rootScope, but it's better practice to create a service for that data.
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('app', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
var viewerAngular = angular.module('ngAppDemo', ['restangular','btford.socket-io'])
.config(function(RestangularProvider) {
$.get('../config/config.xml',
function(data) {
$(data).find('contentserver').each(function() {
serverDetails.contentserver = assignServerDetails($(this));
var restprovider = RestangularProvider;
restprovider.setBaseUrl("http://"+serverDetails.contentserver.ip+":"+serverDetails.contentserver.port+"\:"+serverDetails.contentserver.port);
var Scope=angular.element(document.querySelector('[ng-controller="controllerName"]')).scope();
Scope.init();
});
});