Using AngularJS Service in Controller - angularjs

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.

Related

Error: Can't find variable: WindowsAzure

I am using Azure Mobile services with ionic and I'm trying to create my client in a factory as a singleton. However when trying to use the client like I did normally I keep getting this error Error: Can't find variable: WindowsAzure. Thank you in advance.
Factory
.factory('client', [function(){
var myjsonObj = new WindowsAzure.MobileServiceClient('https://xxx.azurewebsites.net');
return myjsonObj;
}])
Controller where I call it
.controller('loginCtrl', ['$scope', '$stateParams', 'md5', 'Userid', '$state','$ionicSideMenuDelegate','$ionicLoading','client',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams,md5,Userid,$state,$ionicSideMenuDelegate,$ionicLoading,client) {
$scope.UserInfo = {};
$ionicSideMenuDelegate.canDragContent(false);
$scope.show = function() {
$ionicLoading.show({
template: '<p>Loading...</p><ion-spinner></ion-spinner>'
});
};
$scope.hide = function(){
$ionicLoading.hide();
};
$scope.login =function(){
$scope.show($ionicLoading);
if ($scope.UserInfo.password == null){
$scope.UserInfo.password = "fa";
}
var query = client.getTable('clubUser')
.where({ Email: $scope.UserInfo.email, Password: md5.createHash($scope.UserInfo.password) })
.read()
.done(function(results) {
if(results[0] == undefined)
{
$scope.errorText = "Error: Wrong Username/Password";
$scope.$apply();
$scope.hide($ionicLoading);
}
else
{
$scope.hide($ionicLoading);
Userid.setJson(results[0].id);
$state.go('tabsController.qRCode');
}
}, function(error) {
console.dir(error);
$scope.hide($ionicLoading);
});
$scope.UserInfo.password = "";
};
}])
So after looking into the error and not finding any results I decided to add the mobile services plugin manually through adding the script in my index and now it works great! Thank you for helping
You need to ensure the app is in the "ready" state (i.e. all JavaScript libraries are loaded). In Ionic, it's best to use a factory to ensure a singleton. That will also assure you that it is loading at the right time.

how to get variable from different AngularJS file?

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

AngularJS factory return no data first time, but after called interval method it does

Im trying to make a AngularJS factory that provides my app with a list of businesses. But i cant seem to get the variable the first time this is run. But after interval is run, i get the variable.
I get this on the first run on the controller in the page:
angular.js:12783 Error: [$injector:undef] Provider 'businessList' must return a value from $get factory method
But I think my solution is faulty, any how? Can anyone point me in the right direction here? For example is using rootScope here a good idea?
What I want is a globally accessible list of businesses in my app, that is collected on start of visit, and updates itself with a timer. So i dont have to all the time call for induvidial requests from the laravel backend, when i can just find it in that list.. is my idea.
Factory:
myApp.factory('businessList', ['$interval', '$http', '$rootScope',
function($interval, $http, $rootScope) {
function bedriftliste() {
$http.get('get/allebedrifter')
.then(function(result) {
bedrifter = result.data;
$rootScope.bedrifter = bedrifter;
});
return $rootScope.bedrifter;
}
var bedrifter = bedriftliste();
// start periodic checking
$interval(bedriftliste, 5000);
return bedrifter;
}
]);
Controller
myApp.controller('bsC', ['$rootScope', '$scope', 'businessList',
function($rootScope, $scope, businessList) {
$scope.allebedrifter = businessList;
}]);`
I solved this by just doing a http.get if object was null.
if (!$rootScope.allebedrifter) {
$http.get('get/bedrift/' + $scope.tslug)
.then(function(result) {
bedriften = result.data;
$scope.bedriften = bedriften;
});
Seems to work fine like this
Although I am late in pointing out but that doesn't seem to be a proper solution to this problem. You need to make these changes in factory:
myApp.factory('businessList', ['$interval', '$http', '$rootScope',
function($interval, $http, $rootScope) {
function bedriftliste() {
return $http.get('get/allebedrifter');
}
}
]);
and in the controller you'll do something like this:
myApp.controller('bsC', ['$rootScope', '$scope', 'businessList', function($rootScope, $scope, businessList) {
function TestFunction(){
businessList.bedriftliste().then(function successCallback(response) {
$scope.allebedrifter = response.data;
//it will invoke 5 seconds after you receive the response from your factory method, I didn't test it but it will solve your problem
$interval(TestFunction, 5000);
}, function errorCallback(response) {
});
}
}]);

Angularjs cannot get data from service

I'm trying to pass data from one controller to another using a service, however no matter what I'm trying it always returns 'undefined' on the second controller. Here is my service :
app.service('myService', ['$rootScope', '$http', function ($rootScope, $http) {
var savedData = {}
this.setData = function (data) {
savedData = data;
console.log('Data saved !', savedData);
}
this.getData = function get() {
console.log('Data used !', savedData);
return this.savedData;
}
}]);
Here is controller1 :
.controller('HomeCtrl', ['$scope','$location','$firebaseSimpleLogin','myService','$cookies','$window', function($scope,$location, $firebaseSimpleLogin, myService, $cookies, $window) {
loginObj.$login('password', {
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
myService.setData(user);
console.log('myservice:', myService.getData()); // works fine
}]);
And then controller2:
// Dashboard controller
.controller('DashboardCtrl', ['$scope','$firebaseSimpleLogin','myService',function($scope,$firebaseSimpleLogin, $location, myService) {
console.log('myservice:', myService.getData()); //returns undefined
}]);
That is simple code, unfortunately I've been struggling for a few hours now, any suggestion ? Thanks.
Created a fiddle here:
http://jsfiddle.net/frishi/8yn3nhfw/16
To isolate the problem, can you remove the dependencies from the definition for myService and see if that makes it work? Look at the console after you load the fiddle.
var app = angular.module('app', [])
.service('myService', function(){
this.getData = function(){
return "got Data";
}
})
I assume the issue is that you are returning this.savedData in the service. Try returning savedData.
this behaves different in Javascript than in other languages.

Pass parameter from controller to service in Angular

I'm trying to pass a parameter from a controller to service in Angular. Here is the controller:
angular.module('CityCtrl', []).controller('CityController',['$scope', '$http', function($scope,$http,CityService){
$scope.data = "unknown";
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&callback=JSON_CALLBACK').success(function(data){
$scope.data=data;
});
console.log($scope.name);
if($scope.name){
$scope.weather = CityService.get($scope.name);
}
$scope.update = function (zip) {
$scope.zip = zip;
console.log(zip);
$scope.weather = CityService.get({zip: zip});
alert("Hello, " + zip);
}
}]);
and here is the service:
angular.module('CityService', []).factory('City', '$scope'['$http', function($scope,$http) {
return {
get : function() {
return $http.get('/cities/' + zip);
}
}
}]);
When I check the console it is logging the correct value, however, when it tried to run the service it says:
Cannot read property 'get' of undefined
For some reason the zip is not being passed to the service. Any idea where the disconnect is?
You would need to inject City Service, When using explicit dependency annotation, it is all or none rule, you cannot just specify part of your dependencies.
angular.module('CityCtrl', []).controller('CityController',
['$scope', '$http', 'City'
function($scope, $http, City){
Also you cannot inject $scope in a factory (It is available for injection only to controllers, for directive you get it as an argument in the linking function) and looks like you do not need as well.
angular.module('CityService', []).factory('City', ['$http', function($http) {
return {
get : function(zip) {
return $http.get('/cities/' + zip);
}
}
}]);

Resources