2017-08-10 10 views
1

您好我正在開發中angularjs Web應用程序。我想在angularjs中查詢數組。以下是我的代碼片段。無法查詢Java腳本數組中angularjs

var angulararray = []; 
bindleaselistings.bindleaselistingsmethod().then(function(response) { 
    angular.forEach(response.data.data.LeaseList, function(value, key) { 
    angulararray.push(value); 
    }); 
}, function(error) {}); 
console.log(angulararray); 
debugger; 
var found = $filter('filter')(angulararray, { 
    id: accountnumber 
}, true); 
if (found.length) { 
    $scope.selected = JSON.stringify(found[0]); 
} else { 
    $scope.selected = 'Not found'; 
} 

console.log顯示所需的數組。我附上了截圖。 enter image description here

當我調試var found = $filter('filter')(angulararray, { id: accountnumber }, true);我可以看到angulararray是空的。我是否可以知道我在上面的代碼中做了什麼錯誤?任何幫助,將不勝感激。謝謝

+0

你可以張貼在問題的所有代碼,以查找問題。 –

+0

如果帳號是你想要篩選變量,它應該是這樣的:'VAR找到= $過濾器(「過濾器」)(angulararray,ACCOUNTNUMBER,真);' –

+0

這個問題在異步操作的誤解JS的 – MysterX

回答

2

問題是與您的API調用您的code.The執行和它下面的代碼的異步執行,將並行執行。在API調用之外,angulararray的值爲空。您可以在API的成功回調中移動過濾器。

var angulararray = []; 
bindleaselistings.bindleaselistingsmethod().then(function(response) { 
    angular.forEach(response.data.data.LeaseList, function(value, key) { 
     angulararray.push(value); 
    }); 
var found = $filter('filter')(angulararray, { 
    id: accountnumber 
}, true); 
}, function(error) {}); 
console.log(angulararray); 

if (found.length) { 
    $scope.selected = JSON.stringify(found[0]); 
} else { 
    $scope.selected = 'Not found'; 
} 
+0

謝謝Vivz。我更新了截圖。儘管數組中存在accounnumber,但我無法匹配accountNumber。 –

+1

我認爲你應該在過濾器中使用accountNumber – Vivz

1

您有一個異步問題。您的代碼需要在承諾解決後運行。

你在的console.log響應的原因是因爲你的工具顯示變量的實時視圖。所以一旦變量解決了,控制檯中的視圖就會變成已解決的promise的結果。

var angulararray = []; 
bindleaselistings.bindleaselistingsmethod().then(function (response) { 
    angular.forEach(response.data.data.LeaseList, function (value, key) { 
     angulararray.push(value); 
    }); 
    console.log(angulararray); 
    debugger; 
    var found = $filter('filter')(angulararray, { 
     id: accountnumber 
    }, true); 
    if (found.length) { 
     $scope.selected = JSON.stringify(found[0]); 
    } else { 
     $scope.selected = 'Not found'; 
    } 
}, function (error) { }); 
0

你可以改變U濾鏡烏爾變量,有這樣的事情的方式:

var found; 
var len = angulararray.length; 
for(var i=0; i<angulararray; i++){ 
    if(typeof angulararray[i]['AccountNumber'] === 'undefined') { 
    $scope.selected = 'Not found'; 
    } 
    else { 
    found = angulararray[i]; 
    $scope.selected = JSON.stringify(found[0]); 
    } 
}