AngularJS arhitecture

时间:2015-09-02 10:25:35

标签: javascript angularjs architecture

我有以下应用程序,我循环浏览一些数据并显示它。

<div class="thing" ng-repeat="thing in things">
          <h1>{{thing.title}}</h1>
          <p>{{thing.description}}</p>
          <br/>
          <div class="child">
              <!-- ng-repeat="child in ??? -->
              <p>Display child here</p>
          </div>

      </div>

我的数据:

$scope.things = [{
    id: 1,
    title: 'First thing',
    description: 'This is just a thing',
    extra: {
        childs: 3 /* the id of the children */
    }
}, {
    id: 2,
    title: 'Second thing',
    description: 'This is just a thing',
    extra: {}
}, { /* dont displat this object in the ng-repeat="thing in things" */
    id: 3,
    title: 'Child thing',
    description: 'This is a child thing',
    extra: {}
}]

我不明白它如何ng-repeat只是非儿童的东西.child div中显示id为{{1}的元素}。

有人能解释我如何实现这个目标吗?

http://jsfiddle.net/U3pVM/18350/

3 个答案:

答案 0 :(得分:1)

您需要变形数据对象。您也不希望子项显示在列表中。基本上迭代并将子对象移动到额外的键中。即解决参考

**你不希望在显示器中处理复杂的逻辑,因此在你的模型中你应该做所有肮脏的工作。由于您无法更改API,我们将更改API参考

在你的控制器中,我想这将来自API,说你在变量data中有JSON。

//data will be coming from API
/*data = [{
    id: 1,
    title: 'First thing',
    description: 'This is just a thing',
    extra: {
        childs: 3 
    }
}, {
    id: 2,
    title: 'Second thing',
    description: 'This is just a thing',
    extra: {}
}, { 
    id: 3,
    title: 'Child thing',
    description: 'This is a child thing',
    extra: {}
}]; */

然后,你可以在下面变换这个JSON,你会收到你的数据,把这个代码放在你的控制器中。

for(var i in data){
  if(data[i].extra && data[i].extra.childs){
    for(var j in data){
      if(data[j].id == data[i].extra.childs){
        data[i].child = data[j];
        delete(data[j]);
        break;
      }
    }
  }
}

$scope.things = data;//then put the morphed JSON in the $scope.things

HTML将是这样的。注意我在你的JSON中添加了一个有孩子的密钥child

<div class="thing" ng-repeat="thing in things">
    <h1>{{thing.title}}</h1>
    <p>{{thing.description}}</p>
    <br/>
    <div class="child" ng-if="things.child">
        <p>{{thing.child.title}}</p>
        <p>{{thing.child.description}}</p>
    </div>
</div>

答案 1 :(得分:0)

    <div class="thing" ng-repeat="thing in things">
        <h1>{{thing.title}}</h1>
        <p>{{thing.description}}</p>
        <br/>
        <div ng-repeat="(key, value) in thing.extra" class="child">
            <p>{{ key }} : {{ value }}</p>
        </div>
    </div>

答案 2 :(得分:0)

您应该为此目的使用ng-if指令:

<div ng-app>
  <div ng-controller="MainCtrl">

      <div ng-repeat="thing in things">
          <h1>{{thing.title}}</h1>
          <p>{{thing.description}}</p>
          <p ng-if="thing.extra.childs">
              {{thing.extra.childs}}
          </p>
      </div>

    </div>
</div>

JsFiddle:http://jsfiddle.net/nikdtu/op4j7jhj/