我已经浏览了下面SO问题来得到我想要的东西。
create a single html view for multiple partial views in angularjs
AngularJs Include Partial Template
angularjs partial template with specific scope - 看起来很接近我想要的。
但我相信我的情况与他们所有人不同。因此,这个问题。
我有这个HTML
需要重复多次的结构。
<tr>
<td>
Enitity1
</td>
<td>
<input type="radio" name="entity1" value="option1" />
</td>
<td>
<input type="radio" name="entity1" value="option2" />
</td>
<td>
<input type="radio" name="entity1" value="option3" />
</td>
<td>
<input type="radio" name="entity1" value="option4" />
</td>
<td>
<input type="radio" name="entity1" value="option5" />
</td>
</tr>
我想将实体的名称作为参数传递,并根据该参数呈现此 HTML 模板。
我创建了一个如下所示的模板。
<tr>
<td>
{{entity}}
</td>
<td>
<input type="radio" name="{{entity}}" value="option1" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option2" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option3" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option4" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option5" />
</td>
</tr>
我的 Controller
app.controller("entitiesController", ["$scope",
function entitiesController($scope) {
$scope.init = function init(entity) {
$scope.entity= entity;
};
}
]);
我正在尝试为多个实体渲染相同的内容,如下所示 <tbody>
元素。
<ng-include src="Common/entities.html" ng-controller="entitiesController" ng-init="init('Entity1')"></ng-include>
<ng-include src="Common/entities.html" ng-controller="entitiesController" ng-init="init('Entity2')"></ng-include>
<!-- Some more entities here...-->
但是它不起作用。它也不会在控制台中抛出任何错误。
我该如何解决这个问题?处理这个问题的正确方法是什么?是否可以使用模板来处理它,或者我应该手动为所有实体添加 HTML?
最佳答案
您可以拥有directive
为你做这件事。比如,
myApp.directive("myEntity", function() {
return {
restrict: "E",
scope: {
entity: "="
},
templateUrl: "Common/entities.html"
}
})
现在,您可以使用您在 Common/entities.html
中创建的模板也就是说,
<tr>
<td>
{{entity}}
</td>
<td>
<input type="radio" name="{{entity}}" value="option1" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option2" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option3" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option4" />
</td>
<td>
<input type="radio" name="{{entity}}" value="option5" />
</td>
</tr>
最后,像<my-entity entity="entityObj"></my-entity>
一样使用它哪里entityObj
是你的 $scope
中的一个变量(或者相应地,如果您使用 controllerAs
语法)
编辑:其他方法是将指令作为属性而不是元素。
myApp.directive("myEntity", function() {
return {
restrict: "A",
...
}
})
并且,删除 <tr>
从模板中。现在,我们可以这样使用它,
<tbody>
<tr my-entity entity="entityObj">
</tr>
</tbody>
关于javascript - AngularJS 使用参数创建部分模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43863840/