如何打印和分配对象Angular JS的属性

时间:2017-03-21 03:27:18

标签: javascript angularjs

我想知道如何打印并分配包含数组作为属性的以下对象?

var carreers = [
  {
    name: "Law",
    courses: [
      "Law I",
      "Law II"
     ]

  },

2 个答案:

答案 0 :(得分:1)

如果你在谈论角度。使用:

angular.forEach(carreers, function(career) { // this will internally do necessary null checks
    console.log(career); // Print career value.
    career.name = "test1" // Assign Value - value would be updated by reference
    angular.forEach(career.courses, function(course) {
        console.log(course); // Print course value.
        course.push("test12") // Assign Value
    });
});

答案 1 :(得分:0)

应该是:

for(var i =0; i < carreers.length; i++){
     console.log(carreers[i].name);
     console.log(carreers[i].courses);
     for(var j =0; j < carreers[i].courses.length; j++){
         console.log(' - ' + carreers[i].courses[j]);
      }
}

for angular:

<div ng-repeat="data in carreers">
     <p>{{data.name}}</p>
     <div ng-repeat="course in data.courses">
         <p> - {{course}}</p>
     </div>
</div>

在特定职业中添加课程

carreers[0].courses.push("Law III");

展示选择职业的课程

<select id="courses" ng-model="career">
   <option ng-repeat="career in data" value="{$index}">{career.name}</option>
</select>

<div ng-repeat="course in data[career].courses">{course}</div>