在包含HTML片段时分配对象?

时间:2015-04-24 15:26:39

标签: html angularjs

我有以下html片段用简单数据填充div:("list.html"

<div class="eventBox" ng-repeat="element in elements">
   <h1>{{element.title}}</h1>
   <span>{{element.description}}</span>    
</div>

现在我想将这个片段包含在不同的html文档中。它们中的每一个都有不同的列表,它们具有相同的结构。

例如控制器的一部分:

$scope.persons={       
   elements:[
      { title:'John Doe', description:'this is John!'},
      { title:'Jane Doe', description:'The wife of John'}
   ]
}
$scope.buildings={
   elements:[
      { title:'Millerntor', description:'soccer stadium'},
      { title:'Jungfernstieg', description:'exit here for alster boat trips'}´
    ]
}

所以我想要实现的是:

<div ng-controller="MyController">
   <span>Users:</span>
   <div ng-include="list.html" ng-useproperty="{{persons}}
   <span>Buildings:</span>
   <div ng-include="list.html" ng-useproperty="{{buildings}}
</div>

当然没有&#34; ng-useproperty&#34;在AngularJS中。但还有另一种方法可以实现我想做的事情吗?

1 个答案:

答案 0 :(得分:0)

这似乎是angular directive ...

的完美用例
var myListDirective = function() {
  return {
    templateUrl: "list.html",
    scope: {
      "elements": "="
    }
  };
};

您的角度模块看起来像:

var app = angular.module('MainApp', [])
    .directive('listDirective', myListDirective);

然后html看起来像:

<div ng-controller="MyController">
   <span>Users:</span>
   <div list-directive elements="persons"></div>
   <span>Buildings:</span>
   <div list-directive elements="buildings></div>
</div>