2016-03-06 79 views
0

經過一些幫助之前與陣列我試圖檢索monthlyIncome,savePercent和年值並將它們存儲在$scope.monthlyIncome,$scope.savePercent$scope.years

我哪裏錯了?

$scope.data2 = { 
     "$id":"4157e8b1-efa2-4feb-bf75-e907c0e200e0", 
     "$priority":null, 
     "date":1457178818625, 
     "email":"[email protected]", 
     "firstname":"test", 
     "lastname":"Isaacs", 
     "monthly":328947, 
     "monthlyIncome":1200, 
     "regUser":"4157e8b1-efa2-4feb-bf75-e907c0e200e0", 
     "savePercent":10, 
     "years":40 
    }; 

//for each object in data array 
    angular.forEach(data2, function(value, key) { 
     // check if value id is equals to 'monthlyIncome' OR 'savePercent' OR 'years' 
     if (value == 'monthlyIncome' || 
      value == 'savePercent' || 
      value == 'years') { 
     // add it's value with the same key (e.g. $scope.monthlyIncome) 
     $scope.[value] = key; 
     } 
    }); 

任何幫助,不勝感激:)

+0

爲什麼?你已經有了使用'data2'對象的簡單訪問權限。對於那些'$ scope',沒有任何意義。你想解決什麼問題? – charlietfl

+0

我同意@charlietfl,但是如果你堅持這樣做,只需從這個語句中刪除點:'$ scope。[value] = key;' – slackmart

+0

你也混淆了對象的哪個部分是關鍵,哪個是值。學習使用'console.log()'或斷點將幫助你看到什麼不同的變量包含 – charlietfl

回答

0

您需要更好地瞭解angular.forEach函數。 在這種情況下,你應該檢查沒有價值,但鍵:

(function(angular) { 
 
    'use strict'; 
 
    angular.module('app', []) 
 
    .controller('appController', function($scope, $log) { 
 
     $scope.data2 = { 
 
     "$id": "4157e8b1-efa2-4feb-bf75-e907c0e200e0", 
 
     "$priority": null, 
 
     "date": 1457178818625, 
 
     "email": "[email protected]", 
 
     "firstname": "test", 
 
     "lastname": "Isaacs", 
 
     "monthly": 328947, 
 
     "monthlyIncome": 1200, 
 
     "regUser": "4157e8b1-efa2-4feb-bf75-e907c0e200e0", 
 
     "savePercent": 10, 
 
     "years": 40 
 
     }; 
 

 
     //for each key/value in data2 
 
     angular.forEach($scope.data2, function(value, key) { 
 
     // check if key is equals to 'monthlyIncome' OR 'savePercent' OR 'years' 
 
     if (key == 'monthlyIncome' || 
 
      key == 'savePercent' || 
 
      key == 'years') { 
 
      // add it's value with the same key (e.g. $scope.monthlyIncome) 
 
      $scope[key] = value; 
 
     } 
 
     }); 
 

 
    }); 
 
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> 
 
<div ng-app="app"> 
 
    <div ng-controller="appController"> 
 
    <ul> 
 
     <li>{{monthlyIncome}}</li> 
 
     <li>{{savePercent}}</li> 
 
     <li>{{years}}</li> 
 
    </ul> 
 
    </div> 
 
</div>

+0

對不起,我正在努力學習,有時過分複雜的東西,並把它們搞砸了!感謝您的幫助:) – worc

+0

@worc感謝您的投票ups。隨時提問,祝你好運。 ;) – doroshko

+0

謝謝你:) – worc

0

如果你真的需要這些值(注意,你可能複製原語),你已經知道你需要哪些鍵,你爲什麼不直接給他們嗎?

$scope.monthlyIncome = $scope.data2.monthlyIncome; 

在大多數情況下,我寧願通過data2.monthlyIncome這也反映在原始對象data2的更改的原始值從模板訪問它們。

+0

謝謝你的幫助,這是一個更簡單的方法來做到這一點! :) – worc

相關問題