我该如何正确使用角度模板(ng-include)?

时间:2015-02-12 14:52:37

标签: angularjs

我制作了html模板,并希望通过ng-include使用它。

<input class="k-textbox" ng-model="entity.Name">

我想要使用它两次,所以我将它添加到这样的页面

<div ng-include="'/template.html'" ng-init="entity=firstEntity"></div>
<div ng-include="'/template.html'" ng-init="entity=secondEntity"></div>

但结果我得到2个模板&#39; secondEntity&#39;作为数据,什么是正确的用法?

1 个答案:

答案 0 :(得分:1)

这可能是一种可能的用法:

JS:

app.controller("myCtrl1", function($scope) {
  $scope.entity = firstEntity;
}

app.controller("myCtrl2", function($scope) {
   $scope.entity = secondEndity;
}

HTML:

<div ng-controller="myCtrl1">
   <div ng-include="'/template.html'"></div>
</div>
<div ng-controller="myCtrl2">
  <div ng-include="'/template.html'"></div>
</div>

尽管使用指令可以实现需要传递不同模型或配置的可重用模板。

编辑:指令方法:

JS:

app.controller("myCtrl1", function($scope) {
  $scope.entities = {entity1: {}, entity2: {}};
}


app.directive('myDirective', function() {
  return {
    scope: {
      entity: '='
    },
    template: '<input class="k-textbox" ng-model="entity.Name">'
  }
});

HTML:

<div ng-controller="myCtrl1">
   <myDirective entity="entities.entity1"></myDirective>
   <myDirective entity="entities.entity2"></myDirective>
</div>