I'm still a debutant on Angularjs.
I want to inject dynamically a dependency of a service (that I created) in my controller.
But when I code a service with dependencies, I got this error :
Error: Unknown provider: $windowProvider <- $window <- base64
This is the code of the controller.
var base64 = angular.injector(['servicesModule']).get('base64');
console.log("base64", base64.encode("my text will be encoded"));
This code works:
var servicesModule = angular.module('servicesModule', []);
servicesModule.factory('base64', function() {
return {
name: 'base64',
readonly: false,
encode: function(input) {
return window.btoa(input);
},
decode: function(input) {
return window.atob(input);
}
};
});
This code doesn't work :
var extModule = angular.module('ext', []);
extModule.factory('base64', ['$window', function($window) {
return {
name: 'base64',
readonly: false,
encode: function(input) {
return $window.btoa(input);
},
decode: function(input) {
return $window.atob(input);
}
};
}]);
Another problem is when the service is in the same module as the controller.
If the module has dependencies, I doesn't work (I have $routeProvider dependence in my module config) :
Error: Unknown provider: $routeProvider from mainModule
var mainModule = angular.module('main', [],
function($routeProvider, $locationProvider) {
//Some routing code
}
);
JS Fiddles
Same module with dependencies(controller + service) : http://jsfiddle.net/yrezgui/YedT2/
Different module with dependencies : http://jsfiddle.net/yrezgui/YedT2/4/
Different module without dependencies : http://jsfiddle.net/yrezgui/YedT2/5/
Don't call angular.injector() -- this creates a new injector. Instead, inject the already-created $injector into your controller and use it:
So instead of:
var algoController = function($scope) {
$scope.base64 = angular.injector(['main']).get('base64');
};
Do this:
var algoController = function($scope, $injector) {
$scope.base64 = $injector.get('base64');
};
But most of the time you should inject your service directly, rather than dynamically, like so:
var algoController = function($scope, base64) {
$scope.base64 = base64;
};
See also AngularJS dynamically inject scope or controller
Related
I am getting the infamous unknown provider error, and looked into every potential answer up here but I think that I am missing something:
app.js
var myApp = angular.module('myApp', [
'ngResource',
'myAppControllers',
'myAppServices',
'myAppFilters'
]).config([
'$locationProvider',
function(
$locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: false
});
}]);
var myAppControllers = angular.module('myAppControllers', []);
var myAppServices = angular.module('myAppServices', []);
var myAppFilters = angular.module('myAppFilters', []);
Item.js
myAppServices.factory('Item',
function($resource) {
return $resource('/api/items/:id');
});
ItemService.js (1)
myAppServices.factory('itemService',
function($q,
$http,
Item) {
return {
delete: function(id){
// Item, $q and $http are undefined here
return Item.delete({id: id}).$promise;
}
};
});
alternative ItemService.js (2)
myAppServices.factory('itemService', [
'$q',
'$http',
'Item', // If I don't inject it here I can use this service with $q and $http
function($q,
$http,
Item) {
return {
delete: function(id){
return Item.delete(id).$promise;
}
};
}]);
And in my controller:
myAppControllers.controller('ItemsCtrl', [
'$scope',
'itemService',
function(
$scope,
itemService) {
var ctrl = this;
ctrl.ItemService = ItemService;
ctrl.deleteItem = function(id){
ctrl.itemService.delete(id)
.then(function(response){
console.log(response);
}, function (error) {
console.log(error);
});
};
}]);
So if I try like in (1), I am getting undefined.delete is not a function in itemService.
If I try as in (2), the app fails to load with:
Unknown provider: ItemProvider <- Item <- itemService
So what am I doing wrong?
You have multiple issues here.
You need to have myAppServices as a dependency of myAppControllers in order to use it in a controller.
So, following should be how you do it:
var myAppServices = angular.module('myAppServices', []);
var myAppControllers = angular.module('myAppControllers', ['myAppServices']);
In myAppServices module you have Item service which uses $resource but you haven't injected ngResource as a dependency of myAppServices.
Here's your code in plunker without errors
EDIT: Also make sure all your files are included in index.html properly!
i think in $resource ur are missing argument it should look like
$resource('/api/items/:id', {id:'#id'});
Try (1) again , undefined is because of this
and also ur delete should be look like this
return Item.delete({id : id}).$promise;
I have the following code and it works fine:
app.main.js:
angular.module('app', ['ngAnimate', 'ui.router'])
.factory('_', function() {
return window._;
});
angular.module('app').run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
var original = $location.path;
$location.path = function (path, reload) {
if (reload === false) {
var lastRoute = $route.current;
var un = $rootScope.$on('$locationChangeSuccess', function () {
$route.current = lastRoute;
un();
});
}
return original.apply($location, [path]);
};
}]);
bservice:
angular.module('app')
.service('bService', ['$http', '_', function($http, _) { ...
But when I try to separate de factory to a different file I get the Angular Error: $injector:unpr Unknown Provider. This file looks like this:
angular.module('app').factory('_', function() {
return window._;
});
I also made sure that the factory file is included.
Thanks
EDIT
Full error:
Unknown provider: _Provider
I use gulp for the file merges. So everything is in one file.
Gulp didn't like the name factorys. Because of this my factory became damaged in the main .js file.
The solution was to rename the folder to anything els then factorys.
I am having some trouble getting to the controller for my state param. I am using the correct state to link to the next view.
<td><a ui-sref="orders({customerId: cust.id})">View Orders</a></td>
In my config file I am referencing the state that name and the route params. I commented out the resolve object for now. My goal is to get into the controller then pass the correct data. Notice that I am using controllerAs
My initial thought was ({customerId: ctrl.cust.id }) However that did not change the url route.
The url is changing to match the url name but is not connecting to the controller and is not giving me the view.
(function() {
'use strict';
angular
.module('app.orders')
.config(config);
function config($stateProvider) {
$stateProvider
.state('orders',{
// params: {customerid: null},
url:'/customers:customerId',
templateUrl: './components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl',
resolve: {
customerFactory: 'customerFactory',
customerInfo: function( customerFactory, $stateParams) {
return customerFactory.getCustomers($stateParams.id);
}
}
************** my main problem is the resolve. This is blocking me from getting into the next controller. *****************
resolve: {
customerId:[ '$stateParams','customerFactory', function( $stateParams, customerFactory) {
return customerFactory.getCustomers($stateParams.id);
}]
}
})
};
})();
For now my controller is very small. I just want to connect to it. I have checked my networks tab and see GET for the files.
(function() {
// 'use strict';
angular
.module('app.orders')
.controller('OrdersController', OrdersController);
function OrdersController($stateParams) {
console.log('in');
var vm = this;
vm.title = "Customer Orders";
vm.customer = null;
}
}());
I have referenced my module in the main javascript file.
(function () {
'use strict';
angular.module('app', ['app.services',
'app.customers',
'app.orders','ui.router']);
})();
When I comment out the resolve I am able to access the controller. So I know the problem is in the resolve. Here is my service. I am making a request to a Json file with $http request and using .then
Updates Here is my refactored service call I am getting back the correct customer in the console each time.
(function() {
angular
.module('app.services',[])
.constant('_', window._)
.factory('customersFactory', customersFactory);
function customersFactory($http, $log) {
return {
getCustomers: getCustomers,
getCustomer: getCustomer
};
function getCustomers(){
return $http.get('./Services/customers.json',{catch: true})
.then(getCustomerListComplete)
.catch(getCustomerListFailed);
function getCustomerListComplete(response) {
console.log('response.data',response.data);
return response.data;
}
function getCustomerListFailed(error) {
console.log('error', error);
}
}
function getCustomer(id) {
var url = './Services/customers.json';
return $http.get(url, {
catch: true
})
.then(function(response) {
console.log('promise id',id);
var data = response.data;
for(var i =0, len=data.length;i<len;i++) {
console.log('data[i].id',data[i].id);
if(data[i].id === parseInt(id)) {
console.log('data[i]', data[i]);
return data[i];
}
}
})
}
}
}());
There is a working example with your code
It is very hard to guess what is wrong. Based on suggestion I gave you here Have a expression error in ui-sref ... your code seems to be completely valid.
I placed your stuff into this app.orders.js file (the ONLY change is templateUrl path, just for plunker purposes):
angular
.module('app.orders', ['ui.router'])
'use strict';
angular
.module('app.orders')
.config(['$stateProvider', config]);
//config.$inject = ['$stateProvider'];
function config($stateProvider) {
$stateProvider
.state('orders',{
// params: {customerid: null},
url:'/customers:customerId',
//templateUrl: './components/orders/orders.html',
templateUrl: 'components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl'
// resolve: {
// customerId:[ '$stateParams','customerFactory', function( $stateParams, customerFactory) {
// return customerFactory.getCustomers($stateParams.id);
// }]
// }
})
};
// 'use strict';
angular
.module('app.orders')
.controller('OrdersController', OrdersController);
OrdersController.$inject = ['$stateParams'];
function OrdersController($stateParams) {
console.log('in');
var vm = this;
vm.title = "Customer Orders " + $stateParams.customerId;
vm.customer = null;
}
And this is the working template components/orders/orders.html:
<div >
<h3>current state name: <var>{{$state.current.name}}</var></h3>
<h5>title</h5>
<pre>{{ctrl.title}}</pre>
...
When I call it like this:
<li ng-repeat="cust in [{id:1}, {id:2}]"
><a ui-sref="orders({customerId: cust.id})">View Orders - cust ID == {{cust.id}}</a>
</li>
Check it in action here
So, whil my previous answer was about make the state working without resolve, now we will observe few adjustments (and one fix) to make even resolve working.
There is a working plunker, extending the previous one.
FIX
The only fix, the most important change come from this definition:
angular
.module('app.services',[])
.factory('customersFactory', customersFactory);
see the plural in the factory name, the 'customersFactory'. While here:
...my main problem is the resolve. This is blocking me from getting into the next controller....
resolve: {
customerId:[ '$stateParams','customerFactory', function( $stateParams, customerFactory) {
return customerFactory.getCustomers($stateParams.id);
}]
}
we ask for 'customerFactory' (singular, no s in the middle)
Few improvements:
So, this would be our adjusted state def:
$stateProvider
.state('orders',{
// INTEGER is here used to later easily use LO_DASH
url:'/customers{customerId:int}', // int is the type
templateUrl: './components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl',
resolve: {
// wrong name with 's'
//customerId:[ '$stateParams','customerFactory',
// we use customer, because we also changed the factory
// implementation - to return customer related to
// $statePrams.customerId
customer:[ '$stateParams','customersFactory',
function( $stateParams, customersFactory) {
return customersFactory
//.getCustomers($stateParams.id)
.getCustomer($stateParams.customerId)
;
}]
}
})
Now, this is our adjusted factory, and its new method getCustomer
angular
.module('app.services', [])
.factory('customersFactory', customersFactory);
customersFactory.$inject = ['$http', '$log', '$q', '$stateParams'];
function customersFactory($http, $log, $q, $stateParams) {
return {
getCustomers: getCustomers,
getCustomer: getCustomer
};
function getCustomers() {
// see plunker for this, or above in question
}
// new function
function getCustomer(id) {
var url = "customer.data.json";
return $http
.get(url, {
catch: true
})
.then(function(response){
var data = response.data;
var customer = _.find(data, {"id" : id});
return customer;
})
;
}
}
this is our data.json:
[
{
"id" : 1, "name": "Abc", "Code" : "N1"
},
{
"id" : 2, "name": "Def", "Code" : "N22"
},
{
"id" : 3, "name": "Yyz", "Code" : "N333"
}
]
And here we have controller:
OrdersController.$inject = ['$stateParams', 'customer'];
function OrdersController($stateParams, customer) {
console.log('in');
var vm = this;
vm.title = "Customer Orders " + $stateParams.customerId;
vm.customer = customer;
}
a view to show customer
<h3>customer</h3>
<pre>{{ctrl.customer | json}}</pre>
Check it here in action
I've been doing quite a lot of reading about angular dependency injection and factories vs services etc like in this post here - angular.service vs angular.factory
I'm struggling putting it into practise and wonder if you can give me suggestions on how you would do it.
My current code looks like this
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
function mainController($scope, $firebase) {
var db = new Firebase("https://**.firebaseio.com/");
$scope.messages = $firebase(db);
$scope.addItem = function(error) {
if (error.keyCode != 13) return;
$scope.messages.$add({ name: $scope.name, price: $scope.price });
$scope.name = "";
$scope.price = "";
};
}
I decided I wanted to use angular routes and split this basic function up into two different controllers that I would use for my test app. the MainController would just display everything in the firebase db and the AdminController would be able to add messages to it
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
.factory('fireBaseConnectionService', $firebase)
//code in here to connect to firebase and add messages
.controller('MainController', function(fireBaseConnectionService, $scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
//code here to retrieve everything from firebase db
})
.controller('AdminController', function(fireBaseConnectionService, $scope, $routeParams) {
$scope.name = "AdminController";
$scope.params = $routeParams;
//code here to add a row to the db
})
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
redirectTo: '/menu'
})
.when('/menu', {
path: '/menu',
templateUrl: 'partials/menu.html',
controller: 'MainController'
})
.when('/admin', {
templateUrl: 'partials/admin.html',
controller: 'AdminController'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(false);
});
My problem is I don't want to have to connect to the firebase db in each controller. I would like to have a factory that handles this for me and has maybe functions within that that I can call from my controllers to view everything in db and to add something to the db
factory()
As we’ve seen, the factory() method is a quick way to create and configure a service.
The factory() function takes two arguments:
• name (string)
This argument takes the name of the service we want to register.
• getFn (function)
This function runs when Angular creates the service.
angular.module('myApp')
.factory('myService', function() {
return {
'username': 'auser'
}
});
The getFn will be invoked once for the duration of the app lifecycle, as the service is a singleton
object. As with other Angular services, when we define our service, getFn can take an array or a
function that will take other injectable objects.
The getFn function can return anything from a primitive value to a function to an object (similar to
the value() function).
angular.module('myApp')
.factory('githubService', [
'$http', function($http) {
return {
getUserEvents: function(username) {
// ...
}
}
}]);
service()
If we want to register an instance of a service using a constructor function, we can use service(),
which enables us to register a constructor function for our service object.
The service() method takes two arguments:
• name (string)
This argument takes the name of the service instance we want to register.
• constructor (function)
Here is the constructor function that we’ll call to instantiate the instance.
The service() function will instantiate the instance using the new keyword when creating the
instance.
var Person = function($http) {
this.getName = function() {
return $http({
method: 'GET',
url: '/api/user'
});
};
};
angular.service('personService', Person);
provider
These factories are all created through the $provide service, which is responsible for instantiating
these providers at run time.
angular.module('myApp')
.factory('myService', function() {
return {
'username': 'auser'
}
})
// This is equivalent to the
// above use of factory
.provider('myService', {
$get: function() {
return {
'username': 'auser'
}
}
});
Why would we ever need to use the .provider() method when we can just use the .factory()
method?
The answer lies in whether we need the ability to externally configure a service returned by the
.provider() method using the Angular .config() function. Unlike the other methods of service
creation, we can inject a special attribute into the config() method.
from ng-book
All you have to do is just move the firebase connection into the service, and inject that service wherever you want . The connection line will execute the first time your app runs, given that you front load the service when your app runs, as you seem to be doing now:
.factory('fireBaseConnectionService', function($firebase){
var db = $firebase(new Firebase("https://**.firebaseio.com/"));//creating
//the firebase connection this line executes only once when the service is loaded
return{
getMessage:function(){
return db.whatever;
}
}
})
If you load the service script dynamically, on route where you need it, it will only connect to the database when it reaches that route. The code above will create one connection to the database, as the connection line is executed only once.
Just for anyone interested with the help of the answers above and this link - Firebase _ AngularJS this is what I ended up doing
var app = angular.module("martysCoolApp", ['firebase', 'ngRoute'])
.factory('fireBaseConnectionService', ["$firebase", function($firebase) {
var db = new Firebase("https://***.firebaseio.com/");
return {
getMessages: function() {
return $firebase(db);
},
addMessage: function(message) {
var messages = $firebase(db);
messages.$add(message);
}
}
}])
.controller('MainController', ["fireBaseConnectionService", "$scope", function (fireBaseConnectionService, $scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
$scope.messages = fireBaseConnectionService.getMessages();
}])
.controller('AdminController', ["fireBaseConnectionService", "$scope", function(fireBaseConnectionService, $scope, $routeParams) {
$scope.name = "AdminController";
$scope.params = $routeParams;
$scope.addItem = function(error) {
if (error.keyCode != 13) return;
fireBaseConnectionService.addMessage({ name: $scope.name, price: $scope.price });
$scope.name = "";
$scope.price = "";
}
}])
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
redirectTo: '/menu'
})
.when('/menu', {
path: '/menu',
templateUrl: 'partials/menu.html',
controller: 'MainController'
})
.when('/admin', {
templateUrl: 'partials/admin.html',
controller: 'AdminController'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(false);
});
I am new to angulerJS. i have defined a factory to get data from API but when i try to put the factory in a controller i got error.
That is the factory code.
(Function () {
var CategoriesFactory = function($http) {
var factory = {};
factory.getCategorys = function(account_id){
return $http.get('http://localhost:18678/api/Transaction?account_id=2');
};
factory.getTransaction = function(acc_id){
return $http.get('http://localhost:18678/api/Transaction?acc_id=2');
};
factory.getTransactionInCategory = function(category_id, from_date, to_date){
return.$http.get('http://localhost:18678/api/transaction?category='+category_id+'&account=2&from=2015-01- 01&to=2015-12-30');
};
return factory;
};
angular.module('AccApp').factory('CategoriesFactory', CategoriesFactory);
}());
here is the controller.
app.controller('CategoriesController',
function ($scope, $routeParams, $http, CategoriesFactory) {
})
and here is the error.
Unknown provider: CategoriesFactoryProvider <- CategoriesFactory
I guess you must have forgot to inject AccApp into your mai module where you have defined your app.
angular.module("app", ['AccApp']);
Please do something like this.
Hope this helps!
Why are you trying to write angular code in a wierd way ?
The goal of angular is the simplicity
var app = angular.module('AccApp',[]);
app.factory('CategoriesFactory',function($http){// you can cut and paste this factory into a seperate file if you wish
return{
getCategorys:function(account_id){
return $http.get('http://localhost:18678/api/Transaction?account_id=2');
},
getTransaction:function(acc_id){
return $http.get('http://localhost:18678/api/Transaction?acc_id=2');
},
getTransactionInCategory : function(category_id, from_date, to_date){
return.$http.get('http://localhost:18678/api/transaction?category='+category_id+'&account=2&from=2015-01- 01&to=2015-12-30');
};
}
});
Now you can Inject this factory into your controller simply:
app.controller('CategoriesController',function ($scope, $routeParams, $http, CategoriesFactory){
console.log(CategoriesFactory.getCategorys(getCategorys));
});