2016-03-06 108 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

相关问题