在早些时候使用数组后,我尝试检索monthlyIncome
,savePercent
和年数值并将其存储在$scope.monthlyIncome
,$scope.savePercent
和{{ 1}}。
我哪里错了?
$scope.years
任何帮助都非常感谢:)
答案 0 :(得分:0)
如果您确实需要这些值(请注意您可能复制基元)并且您已经知道需要哪些键,为什么不直接分配它们?
$scope.monthlyIncome = $scope.data2.monthlyIncome;
在大多数情况下,我更希望通过data2.monthlyIncome
从模板访问它们,这也反映了原始对象data2
中原始值的更改。
答案 1 :(得分: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": "a@b.com",
"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>
&#13;