如何在AngularJS中填充动态变量

时间:2016-06-20 22:44:21

标签: javascript angularjs dynamic-variables

以下代码给出了错误“无法读取属性PERSON1 of null”。如果我注释掉我尝试分配动态变量并取消注释警报线的行,它会弹出警报,并显示每个连续的人的姓名。

    function fillInternalRepData() {

    var internalRepList = null;

    console.log("Querying Table for internal reps");
    queryTable(//..blabla..//, "false", function (callbackResp) {
        internalRepList = callbackResp;

        //            alert("TRIGGERED"); //WORKS
        //            alert(internalRepList.length); //WORKS
        angular.forEach(internalRepList, function (rep) {
            repName = rep.such;
            $scope.internalReps[repName].such = repName;
            //alert(repName); //WORKS WHEN LINE ABOVE IS COMMENTED OUT
        });


    }); //get list of internal reps

我只想创建/添加到$ scope.internalReps对象,以便我可以像$ scope.internalReps.PERSON1.Name =“Whatever”一样添加内容。 $ scope.internalReps.PERSON1.Salary = 100000;

2 个答案:

答案 0 :(得分:0)

尝试在forEach循环之前为“internalReps”添加一个空对象。它看起来不像你已经声明了对象,所以它不能动态地添加到空对象。

$scope.internalReps = {};
angular.forEach(internalRepList, function (rep) {
  repName = rep.such;
  $scope.internalReps[repName] = {}; 
  $scope.internalReps[repName].such = repName;
  //alert(repName);
});

答案 1 :(得分:0)

var internalReps = {}; 
angular.forEach(internalRepList, function (rep) { 
repName = rep.such; 
internalReps[repName] = { such: "" }; 
internalReps[repName].such = repName; 
//alert(internalReps[repName].such); 
});

那很有用。谢谢你的帮助!