2014-02-13 86 views
0

選擇電流值不能從我的列表中設置當前用戶從陣列中angularjs

提交表單

[{"name":"Erich","surname":"Josh","email":"[email protected]","age":"22","tel":"32423432432"}] 

的setCurrent用戶功能

$scope.currentUser = null; 

    $scope.setCurrentUser = function(name) { 
     $scope.currentUser = $scope.users[name]; 
    }; 

後,我要點擊我的數組名稱,然後顯示有關該用戶的完整信息,但我不能選擇當前。

我在做什麼錯了?

+0

內plunkr /的jsfiddle請 – Anand

回答

0

的你在做什麼,結果是

$scope.currentUser = $scope.users[name]; 

將是

$scope.currentUser = "Erich"; 

因爲你得到的值(名稱在這種情況下是關鍵)

正確的解決方案,首先聲明用戶陣列

var users = [{"name":"Erich","surname":"Josh","email":"[email protected]","age":"22","tel":"32423432432"},{"name":"Another","surname":"Josh","email":"[email protected]","age":"22","tel":"32423432432"}]; 

現在重寫功能setCurrentUser

$scope.setCurrentUser = function(name) { 
    for(var i = 0; i < users.length; i++) 
    if(users[i].name == name){ 
     $scope.currentUser = users[i]; 
     break; 
    } 
} 

現在,你有充分的信息$ scope.currentUser

+0

TNX它的工作。一個問題:這是不好的語法這樣寫嗎? 'var users = $ scope.users = [];' – user3305175

+0

是的,你可以編寫這段代碼) –

+0

它是Javascript,幾乎沒有「壞」語法之類的東西;) – citizenslave