Reputation: 4341
Difficult to reproduce, so I will try to explain instead.
Within a factory of angularjs I have a function like this
angular.module('my').factory('Database', ['$window', 'Raw', function($window, Raw) {
return {
read: function() {
where Raw is another factory defined below that returns a data string
Then I do this:
var lines = [];
lines = Raw.data.split("*");
which gives me an array of strings.
The strange behaviour is that it gives an error as lines[0] is undefined. I can solve this error by adding an alert
var lines = [];
lines = Raw.data.split("*");
alert(lines[0])
which shows me the expected string. But it does not work if I put a console.log command instead.
So, what's going on??
Cheers,
Upvotes: 1
Views: 101
Reputation: 77920
Sounds like you get Raw.data
by async way and when you try split it, it still undefined
.
If Raw.data
returns promise, use then()
callback than, something like:
var myModule = angular.module('myModule', []);
myModule.controller('myController', ['$scope', 'Database', function($scope, Database) {
$scope.text = Database.read();
}]);
myModule.factory('Database', ['$window', 'Raw', '$q', function($window, Raw, $q) {
return {
read: function() {
var deferred=$q.defer();
Raw.data().then(function(data) {
lines = data.split("*");
deferred.resolve(lines);
});
return deferred.promise;
}
}
}]);
myModule.factory('Raw', ['$window', '$q', function($window, $q) {
return {
data: function() {
var data = "blah * blah";
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
}]);
Demo Fiddle
Upvotes: 1