I am getting an array in AngularJs with factory function. This is the console
Array[0]
0: "value1"
1: "value2"
length:2
But when i want to get the length of the array
console.log(array.length)
getting data from mysql in loopback
app.factory("getFoo", function(Communications){
return {
getCommi: function(val,id){
var array = [];
var myVals = Communications.find({
filter: {
where: {
and : [{
communications_type_code : val
},{
object_id : id
}]
}
}
}, function(data){
for(var i=0; i< data.length; i++){
array[i] = data[i].contact_value;
}
return array;
});
return array;
}
}
});
The controller look like:
app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);
setTimeout(function(){
$scope.formModel.emails = [];
for(var index=0; index < $scope.emails.length; index++){
$scope.emails = emails;
}
}, 0)
}])
I get that the length is 0. Why is that?
This is a timing issue. The first time you ask for the length it is indeed 0, but when you inspect the object a few seconds later with Chrome Dev Tools you are inspecting the live object which has now been filled.
You can confirm this by using setTimeout
setTimeout(function(){
console.log(array);
}, 0)
You can checkout this link for further explanation
UPDATE
In angular, use $timeout
instead of setTimeout
. Like this:
$timeout(function(){
console.log(array);
}, 0)
The length property of an Array in JavaScript is immutable. You can either set an Array's size by defining how many properties will be in there: var a = new Array(2), or by just passing in your values: var a = ['value1', 'value2'].
You mix async with sync approaches here.
Communications.find
is async but you use it in getCommi
like sync function.
When you call getCommi
the function return immediately with empty array
.
Please change according below.
app.factory("getFoo", function(Communications){
return {
getCommi: function(val,id, cb){
var array = [];
var myVals = Communications.find({
filter: {
where: {
and : [{
communications_type_code : val
},{
object_id : id
}]
}
}
}, function(data){
for(var i=0; i< data.length; i++){
array[i] = data[i].contact_value;
}
cb(null, array);
});
}
}
});
and
app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
getFoo.getCommi(3,1, function(err, emails){
$scope.formModel.emails = [];
for(var index=0; index < $scope.emails.length; index++){
$scope.emails = emails;
}
});
}])
DISCLAIMER : I don't know angular.
尝试这个,
console.log(array[0].length)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.