【问题标题】:AngularJS rendering different template inside ng-repeat using ng-viewAngularJS 使用 ng-view 在 ng-repeat 中渲染不同的模板
【发布时间】:2014-07-09 16:49:18
【问题描述】:

很抱歉,我无法提供有关此问题的任何代码 sn-p,我是 AngularJS 的新手。

<div ng-repeat="item in list" ng-view></div>

使用上面的代码,是否可以渲染依赖于item.type 属性的不同模板。我期待这样的结果:

  • item.type == "image" 返回: &lt;div&gt;&lt;img src="'IMAGE_URI'"&gt;&lt;/div&gt;
  • item.type == "text" 返回: &lt;div&gt;&lt;p&gt;TEXT&lt;/p&gt;&lt;/div&gt;

到目前为止,我已经为 item.type 的枚举创建了一个模板 html。使用 AngularJS 可以解决这个问题吗?我最近了解到ng-view 伴随着ng-route

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angularjs-routing ng-view


    【解决方案1】:

    我认为您可以这样做的一种方法是使用“ng-if”有条件地包含 html:

     <div ng-repeat="item in list">
          <div ng-if="item.type == 'image'><img src="'IMAGE_URI'"></div>
          <div ng-if="item.type == 'text'><div><p>TEXT</p></div>
     </div>
    

    【讨论】:

      【解决方案2】:

      你只能有一个 ng-view,
      看看这个answer

      来自documentation for ng-view:

      ngView is a directive that complements 
      the $route service by including the rendered
      template of the current route into the main
      layout (index.html) file.
      
      Every time the current route changes,
      the included view changes with it according 
      to the configuration of the $route service.
      
      Requires the ngRoute module to be installed.
      

      你要找的是ng-include,结合ng-switch, 看看这个answer,了解如何将两者结合起来。

      ng-include 创建一个新的子作用域,该作用域又继承自控制器。 请查看answer 以了解有关该主题的更多信息。

      【讨论】:

      • 后续问题。如果我使用ng-include,我仍然可以访问scope,以便能够使用一些数据绑定功能?
      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 2014-01-16
      • 2014-07-06
      • 1970-01-01
      • 2017-01-26
      • 2013-09-17
      相关资源
      最近更新 更多