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);
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 want to create a factory for routing purposes. I want to encapsulate this in a factory because I want to exchange info from one page to another. I don't know if this is the best practice. Please tell me if there are other better ways.
This is my controller:
angular.module('app.core')
.controller('mainCtrl', ['ShowService', 'ChangeViews', function(ShowService, ChangeViews){
var vm = this;
vm.namespaces = [];
vm.servers = [];
vm.p4path = '';
vm.gitpckname = '';
vm.server = '';
vm.ns = '';
ShowService.getNamespaces().then(function(response){
var data = angular.fromJson(response.data);
angular.forEach(data.namespaces, function(value){
vm.namespaces.push(value);
vm.initNamespaceSelVal = vm.namespaces[0];
vm.ns = vm.namespaces[0];
});
});
ShowService.getServers().then(function(response){
var data = angular.fromJson(response.data);
angular.forEach(data.servers, function(value){
vm.servers.push(value);
vm.initServerSelVal = vm.servers[0];
vm.server = vm.servers[0];
});
});
vm.doClick = function(value){
if(value){
var body = {};
body['server'] = vm.server;
body['p4path'] = vm.p4path;
body['packagename'] = vm.gitpckname;
body['namespace'] = vm.ns;
ShowService.getBraches(body).then(function(response){
console.log(response);
//$location.path('/hidden');
//ChangeViews.changeView('/hidden');
});
};
};
}]);
In the above code, I injected two custom made factories into controller. The "ShowService" works properly but the "ChangeViews" returns some errors.
Using $location service inside the controller(the commented line) works.
The factory code is:
angular
.module('app.services')
.constant('BASE_URL', 'http://localhost:8066')
.factory('ShowService', dataService)
.factory('ChangeViews', changeViews);
function dataService($http, BASE_URL){.....}
function changeViews($location, view){
var data = {
'changeView': changeView,
};
function changeView(view){
return $location.path(view);
};
return data;
}
The path to the html template is routed.
The error I'm receiving when injecting the ChangeViews factory is:
"Error: [$injector:unpr] http://errors.angularjs.org/1.5.5/$injector/unpr?p0=viewProvider%20%3C-%20view%20%3C-%20ChangeViews
What I'm missing?
Thank you
The problem is that you don't have injectable service named view, hence the unknown provider error.
Remove view from changeViews parameters list:
function changeViews($location) {
var data = {
changeView: changeView
};
function changeView(view) {
return $location.path(view);
};
return data;
}
I keep getting errors while injecting a factory in to a controller. It worked in a case where the controller is simple. It fails when the page and the controller has special components like ng-flow or ng-grid.
var carouselController = carouselApp.controller('carouselController', ['CMSFactory', function ($scope,CMSFactory) {
// MY CODE HERE...
}
var CMSServices = angular.module('api.services', [ 'ngResource' ]);
CMSServices.factory('CMSFactory', function($http, $q) {
var CMSService = {};
CMSService.saveSiteInfo = function(data) {
// MY CODE HERE...
};
CMSService.addSlide = function(data) {
// MY CODE HERE...
};
return CMSService;
});
I get TypeError: undefined is not a function error. If I remove the factory injection code works fine.
Appreciate any help...
You're not declaring $scope in your array of dependencies:
Change:
var carouselController = carouselApp.controller('carouselController', ['CMSFactory', function ($scope,CMSFactory) {
To:
var carouselController = carouselApp.controller('carouselController', ['$scope', 'CMSFactory', function ($scope,CMSFactory) {
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();
});
});
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.