how to get variable from different AngularJS file? - angularjs

How is it possible to get $scope variable from different file (with different module)? For example, I have two files - index.js and login.js, I want to get username from login.js in index.js. I tried to use services but couldn't achieve that goal. The controller doesn't see service in another angular file.
Codes partially are given below:
bookApp.controller('bookListCtrl', ['sharedProperties', function($scope, $http, sharedProperties) {
'use strict';
$scope.name = "Alice";
console.log("in book controller");
console.log("getting login name: "+sharedProperties.getProperty());
and
var authentication = angular.module('authentication', []);
authentication.service('sharedProperties', function () {
var property = 'First';
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
I got this exception -
angular.min.js:63 Error: Unknown provider: authentication.sharedPropertiesProvider <- authentication.sharedProperties
at Error (native)
at

There are 2 problems in the given implementation. The first problem is that the module 'authentication' needs to be a dependency for the consuming modules. The second problem is in the declaration of bookListCtrl. It needs to be defined as follows.
bookApp.controller('bookListCtrl', ['$scope','$http','sharedProperties', function($scope, $http, sharedProperties){
}]);

Can you give an example how you've used services?
Normally if you define controllers like:
app.controller('LoginController', ['UserService', function($scope) {
$scope.someMethod = function(){
// push information to service
UserService.username = $scope.username;
}
}]);
app.controller('IndexController', ['UserService', function($scope) {
// pull information from service
$scope.username = UserService.username;
}]);
It should work. I must suggest you thou to use Controller as instead of $scope. More info here: https://docs.angularjs.org/api/ng/directive/ngController

Related

Using AngularJS Service in Controller

Service:
app.service('myService', ['$scope', '$timeout', function($scope, $timeout){
return {
fn: function(messageTitle, messageContent) {
$timeout(function() {
$scope.fadeMessageSuccess = true;
}, 3000);
}
}
}]);
Controller:
app.controller("AccountCtrl", ["$scope", "Auth", "$timeout", "myService",
function($scope, Auth, $timeout, myService) {
myService.fn();
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
// Create a new user
Auth.$createUserWithEmailAndPassword($scope.accountEmailAddress, $scope.accountPassword)
.then(function(firebaseUser) {
$scope.message = "User created with uid: " + firebaseUser.uid;
console.log($scope.message);
}).catch(function(error) {
$scope.error = error;
console.log($scope.error);
});
};
}
]);
I'm trying to create a service so that I can use a function in multiple controllers but I'm have trouble getting this first one working. This is the error message I'm getting in console:
angular.js:13550Error: [$injector:unpr]
Just an observation: doesn't look like you're passing anything to the function when you're calling it. And not sure if you're wanting to add any more functionality to the service, but I think you can return the function directly and just call "myService(title, content);". But I don't think those issues would cause what you're encountering.
It looks like you were trying to return an object (a la the .factory() function) when you were trying to use .service(). Here is a dead simple explanation for .factory, .service, and .provider.
As pointed out by user2341963, injecting $scope into a service doesn't make much sense.
Also, are you sure all of your dependencies are defined and available to Angular?
Here is an example Plunkr of using a service in a controller.

injecting service into controller not working

Am new to angularjs. I am trying to use angular service to post data but its throwing below error
angular.js:12520 Error: [$injector:unpr] Unknown provider: frontendServiceddProvider <- frontendServicedd <- CustSignupCtrl
service.js
app.service('frontendService', function frontendService ($http, $q, $rootScope){
var list = this;
list.registerCust = function(data){
var defer = $q.defer();
$http({
url: $rootScope.endPoint,
method: "POST",
data: data
})
.success(function(res){
console.log("Successfull!");
defer.resolve(res);
})
.error(function(err, status){
console.log("Failed !");
})
return defer.promise;
}
return list;
});
customer_signup.js
app.controller('CustSignupCtrl', ['$scope', '$filter','frontendService', '$http', 'editableOptions', 'editableThemes','notify','notification','$appConstants',
function('$scope', '$filter','frontendService', '$http','editableOptions', 'editableThemes','notify','notification','$appConstants'){
$scope.pw1 = '';
$scope.registerCustomer = function (data) {
return frontendService.registerCust(data)
}
$scope.signupcustomer = function(){
var payload= {
first_name: $scope.custForm.fname,
last_name: $scope.custForm.lname,
phone: $scope.custForm.phone,
email:$scope.custForm.email,
username:$scope.custForm.username,
password:$scope.custForm.pw1,
usertype:3
}
console.log("inside function");
$scope.registerCustomer(payload).then(function(data){
notification.success(data.result);
},function(err){
notification.error("Error: contact system admin");
});
}
}
])
I have given reference of both js files in index.html.. not getting where am doing wrong.. can anyone help
app.controller('CustSignupCtrl', ['$scope', '$filter', 'frontendService', '$http', 'editableOptions', 'editableThemes','notify','notification','$appConstants',
function($scope, $filter, frontendService, $http, editableOptions, editableThemes, notify, notification, $appConstants){
$scope.pw1 = '';
});
Whatever you inject into controller, should be in the same order.
Remove quotes accross the injectables inside function.
This can be a dependency injection mismatch sort of problem
AngularJS injects object into the function as it sees them inside []
For example if you declare a function inside your js file, say like this
var app = angular.module('app',[]);
app.controller('maincntrl',function($scope){
});
var search = function($scope,searchtext,searchfilters,searchareas)
{
return 'result'
}
console.log(angular.injector.annotate(search));
The result you shall get in your console will be
["$scope","searchtext","searchfilters","searchareas"]
AngularJS parses the function parameters as an array
It goes through each array elements and the moment it sees "$scope", it injects scope object into that position
Now the syntax which you have used is basically used for minification
So according to your declaration
app.controller('CustSignupCtrl', ['$scope','frontendService', '$filter','frontendService', '$http', 'editableOptions', 'editableThemes','notify','notification','$appConstants',
function('$scope', '$filter','frontendService', '$http','editableOptions', 'editableThemes','notify','notification','$appConstants'){
});
So
$scope--> shall be injected into $scope
frontendService-->shall be injected into $filter
$filter--> shall be injected into frontendService
.
.
.
so on
Also the errors(which you mentioned in comments) are occurring because you have declared function parameters as strings in which case the dependency injection is not happening. Fixing these things shall solve your problem

Angular Service injected not working

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 [].

Unknown provider in .config() with custom Provider

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;
}]);

How to get an AngularJS controller in a filter

Is it possible to use dependency injection to reference a controller inside of a filter? I tried the following:
app.filter('myFilter', function(MyCtrl) {...})
app.controller('MyCtrl', function(...) {})
But I get an error that MyCtrl dependency cannot be found.
If you are trying to access some sort of state information inside your filter, you should consider moving that functionality into a service and then accessing the service from both your filter and your controller.
I can't come up with a reason to want to instantiate a controller inside a filter, so perhaps if you gave a bit more background about the problem you are trying to solve we could give you more tailored information on how best to implement it.
In any case, here's a Plunk showing a filter and a controller sharing some data:
app.controller('MainCtrl', function($scope, MyService) {
$scope.text = "ABCDEFG";
$scope.data = 2;
$scope.$watch('data', function() {
MyService.setData($scope.data);
})
});
app.service('MyService', function() {
service = {}; // the service object we'll return
var dataValue = 'data';
service.setData = function(data) {
dataValue = data;
}
service.getData = function() {
return dataValue;
}
return service;
});
app.filter('truncate', function(MyService) {
return function(input) {
return input.substring(0, MyService.getData());
};
});
If you check out the plunk, note that you have to update the text to get the filter to re-run with an updated number of characters to show.
actually this is the way:
Just inject $filter to your controller
.controller('myController', function($scope, $filter) {...});
Then it does not matter where you want to use that filter, just use it like this:
$filter('filterName');
If you want to pass arguments to that filter, do it using separate parentheses:
.controller('myController', function($scope, $filter) {
$filter('filterName')(argument1,argument2);
});

Resources