Angular是否理解关系模型?

时间:2014-09-09 15:53:18

标签: angularjs

我刚刚开始阅读有关Angular的内容。我理解Angular在处理ng-repeat绑定时需要嵌套模型,例如:

    var model =  {

          states:
             [ 
              { state: "NY", cities: ["NYC", "Albany", "Schenectady"] },
              { state: "PA", cities: ["Philadelphia", "Pittsburgh", "Scranton"]}
             ] 
    }

编辑:产生这个:

           <ul>NY
             <li>NYC</li>
             <li>Albany</li>
             <li>Schenectady</li>
           </ul>
           <ul>PA
             <li>Philadelphia</li>
             <li>Pittsburgh</li>
             <li>Scranton</li>
           </ul>

但Angular是否也理解如何使用这样的关系模型进行ng-repeat绑定?

    var model = {

          states: [ {state:"NY"}, {state: "PA"}],
          cities: [ 
                   {state: "NY", city: "NYC"}, 
                   {state: "NY", city: "Albany"}, 
                   {state: "NY", city: "Schenectady"},
                   {state: "PA", city: "Philadelphia"},
                   {state: "PA", city: "Pittsburgh"},
                   {state: "PA", city: "Scranton"}
                   ]
           }

2 个答案:

答案 0 :(得分:2)

是的,当您拥有关系模型时,可以使用过滤器实现相同的行为。

第一种情况:

var model =  {

      states:
         [ 
          { state: "NY", cities: ["NYC", "Albany", "Schenectady"] },
          { state: "PA", cities: ["Philadelphia", "Pittsburgh", "Scranton"]}
         ] 
}

HTML:

<ul ng-repeat="state in model.states">
  {{state}} 
  <li ng-repeat="city in state.cities">{{city}}</li>
</ul>

第二种情况:

var model = {

      states: [ {state:"NY"}, {state: "PA"}],
      cities: [ 
               {state: "NY", city: "NYC"}, 
               {state: "NY", city: "Albany"}, 
               {state: "NY", city: "Schenectady"},
               {state: "PA", city: "Philadelphia"},
               {state: "PA", city: "Pittsburgh"},
               {state: "PA", city: "Scranton"}
               ]
       }

HTML

<ul ng-repeat="state in states">
 {{state}}
 <li ng-repeat="city in cities | filter:{state: state}">{{city.city}}</li>
</ul>

答案 1 :(得分:0)

<div ng-repeat="(key,value) in model">...</div>

这可能是您尝试实现的目标。 div的内容现在可以为对象的每个属性引用{{ key }}{{ value }}