Data from factory is undefined - javascript

I'm trying to play with angularJS.
I wrote this easy example :
var myApp = angular.module('myApp',[]);
myApp.factory( 'Data' , function() {
return { message: "I'm data from a service" }
});
function FirstCtrl($scope) {
$scope.data = Data;
}
function SecondCtrl($scope) {
$scope.data = Data;
}
but i get the following error message:
ReferenceError: Data is not defined
What am i doing wrong

You're using Data which you never defined in the global scope.
Instead, since you defined it with Angular's dependency injection mechanism:
var myApp = angular.module('myApp',[]);
myApp.factory( 'Data' , function() {
return { message: "I'm data from a service" }
});
// angular will figure it out based on parameter name
myApp.controller("FirstCtrl",function($scope,Data) {
$scope.data = Data;
});
fiddle

var myApp = angular.module('myApp',[]);
myApp.factory( 'Data' , function() {
return { message: "I'm data from a service" }
});

Related

why the factory is not able to access inside the controller

I have created notification factory and pass inside controller,Inside controller when assign the factory to the scope getting error.
alertsManager
MyApp.factory('alertsManager', function() {
return {
alerts: {},
addAlert: function(message, type) {
this.alerts[type] = this.alerts[type] || [];
this.alerts[type].push(message);
},
clearAlerts: function() {
for(var x in this.alerts) {
delete this.alerts[x];
}
}
};
});
var LoginController = function($scope,$rootScope,alerts,alertsManager)
{
$scope.alerts = alertsManager.alerts;
// getting error.
**angular.js:11594 TypeError: Cannot read property 'alerts' of undefined**
}
LoginController.$inject = ['$scope', '$rootScope','alerts','alertsManager'];
**why factory not able to access inside controller.*
Try something like below .
code:
var myApp = angular.module('myApp', []);
myApp.factory('alertsManager', function() {
return {
alerts: {'alert':"i'm from factory service"},
addAlert: function() { //code },
clearAlerts: function() { //code }
}
});
myApp.controller('MyCtrl',['$scope','alertsManager', function($scope, alertsManager) {
$scope.test = alertsManager.alerts.alert;
}]);
Note : Inject factory service into Controller
working sample here .
No need to inject 'alerts' as a dependency in controller.
Sorry ..very stupid question .. Are you sure Do you include these files in Index.html?
like this:
<script src="app/services/alertsManager.js"></script>

AngularJS Factory, Service and HTTP Usage

I am new to learning angular and having trouble understand some of the basics.
I have my controller line shown below:
$scope.test = fileLoader.loadFile();
And my factory service shown below:
angular.module('myWellnessTrackerApp')
.factory('fileLoader', function($http) {
return{
loadfile : function(fileLoc){
$http.get('data/sideEffects.json').success(function(data) {
// you can do some processing here
return data;
});
}
};
});
Which throws an error. But when my controller line is
$scope.test = fileLoader.data;
And my service is
angular.module('myWellnessTrackerApp')
.factory('fileLoader', function($http) {
var obj = {content:null};
$http.get('data/sideEffects.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
Which i don't understand and I would like to be able to understand how to make services in particularly a HTTP service wrapper for requesting a page or local file and having it returned.
Thanks
You can't just do
$scope.test = fileLoader.loadFile();
loadFile is an async call, and you can't return from that! You can use .then to continue the promise pattern. Your factory would change to:
loadFile : function(fileLoc){
return $http.get('data/sideEffects.json').then(function(result) {
// you can do some processing here
return result.data;
});
}
And your controller:
fileLoader.loadFile().then(function(data) {
$scope.test = data;
});

Reference $scope variables from within $http request angular

I am very new to angularjs and am having a hard time trying to figure out this issue.
Basically, we are using a factory to request data for our application. When the factory returns a promise, we were hoping that the data inside the returned promise that was defined in our scope, would be able to be used, but it is only returning as text on the page.
For example: We have defined $scope.name in our controller:
app.controller('AccountController',function($scope,Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().success(function(data) {
$scope.news.push(data);
});
});
so the factory (getSnapshot) will return something like "Hello {{name}}" from an $http request as follows:
app.factory('Account',function($http) {
return {
getSnapshot : function() {
return $http.get('data.php');
}
}
});
Is it possible to allow the factory to access /use {{name}} from the $scope?
You will need to use internal Angular $interpolate service:
app.controller('AccountController', function($scope, $interpolate, Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().success(function(data) {
var text = $interpolate(data)($scope);
$scope.news.push(text);
});
});
Use $q and promises thanks to #dfsq's answer on my post similar to this. Works perfectly.
Here's a plunker.
// Factory method.
app.factory('Account', function($http, $q) {
var data;
return {
getSnapshot: function() {
return data ? $q.when(data) : $http.get('data.json').then(function(response) {
data = response.data;
return data;
})
}
}
});
// Controller method.
app.controller('AccountController', function($scope, Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().then(function(data) {
$scope.news = data;
});
});

AngularJS how to set variable in $http success function of dependency provider

I'm newbie in angularjs and I'm trying to create new provider. This is my code:
myApp.provider('$Data', function() {
this.URL = 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true';
this.$get = $get;
$get.$inject = ['$http', '$q'];
function $get($http, $q) {
var that = this;
return {
isConnected: function() {
var bIsConnected = 'Default';
$http({method: 'GET', url:that.URL}).then(function (data) {
bIsConnected = 'Yes';
alert('Run this code!');
}, function (data) {
bIsConnected = 'No';
});
return bIsConnected;
}
}
}
});
Jsfiddle demo:
http://jsfiddle.net/0udm9/9dPsb/6/
After I run $Data.isConnected(), the result is always 'Default' although browser show the alert box. I think it's from success function is not of $get. And I have to use provider, not service or factory for this case. Can I do anything to fix this issue?
Thanks,
You have to use promise in your code.
DEMO
Provider:
isConnected: function() {
var deferred = $q.defer();
$http.get(that.url).then(function(res) {
deferred.resolve('Yes');
console.log('example:success', res);
}, function(err) {
deferred.resolve('No');
console.log('example:error', err);
});
return deferred.promise;
}
Controller:
$Data.isConnected().then(function(data) {
$scope.data = data;
});
// UPD
You must use objects if you need to use return values with async code.
DEMO
// UPD 2
FRESH DEMO LINK

Angularjs - How to combine two objects obtained with ngresource

How to combine two objects obtained with ngressource.
Each 5 seconds, i call my service to obtain a message and i want to add a new message with the olders.
My Json message :
[
{"age": 0,"id": "my first tweet","name": "Hello Sarah","snippet": "It's fabulous"},
{"age": 1,"id": "my second tweet","name": "Hello dude !","snippet": "It's fabulous"}
]
My Service :
'use strict';
/* Services */
var listlogServices = angular.module('listlogServices', ['ngResource']);
listlogServices.factory('Log', ['$resource',
function($resource){
return $resource('log/log1.json', {}, {
query: {method:'GET', params:{}, isArray:true}
});
}]);
My controller and functions
'use strict';
var app = angular.module('appRecupTweetApp');
app.controller('TimerCtrl1', function TimerCtrl1($scope, Timer){
$scope.$watch(function () { return Timer.data.myTab; },
function (value) {
$scope.data = value ;
//$scope.data.push(value);
//$scope.data = $scope.data.concat(value);
}
);
});
app.service('Timer', function ($timeout, Log) {
var data = { myTab: new Array()};
var updateTimer = function () {
data.myTab = Log.query();
$timeout(updateTimer, 5000);
};
updateTimer();
return {
data: data
};
});
I try to combine my object with 'push' and 'concat' but is not right.
Corrected error (Angular says : $scope.data is undefined )
Could i make this operation in my 'Timer' service or in my controller and what is the good solution.
Online demo : plnkr.co/edit/Vzdy9f7zUObd71Lm86Si
Thank's
Guillaume
You just have to initialize $scope.data in you TimerCtrl1 controller.
app.controller('TimerCtrl1', function TimerCtrl1($scope, Timer){
$scope.data=[];
$scope.$watch(function () { return Timer.data.myTab; },
function (value) {
$scope.data = value ;
//$scope.data.push(value);
//$scope.data = $scope.data.concat(value);
}
);
});

Categories

Resources