我已经接管了一些代码。看起来像这样:
<div id="init"
data-admin-template
ng-show="ss.display.init"
data-template-url="init.html">
</div>
有一个指令adminTemplate:
app.directive('adminTemplate', ['stateService', function (stateService) {
return {
restrict: 'A',
templateUrl: function (elem, attrs) {
return "/Content/app/admin/templates/" + attrs.templateUrl;
},
link: function (scope, element, attrs) {
scope.stateService = stateService;
}
};
}]);
我对模板不是很熟悉,似乎该指令并没有真正做很多事情。没有指令,有没有办法做到这一点?
正如@Oli在评论中所说,ng-include
绝对是一种解决方案。还有其他一些-角度喜欢为您提供足够的选择,使您怀疑自己-但我想知道通过更改它实际上会获得什么。
有了ng-include
你需要一个控制器添加到您的HTML,以供应stateService
(如果你没有在这里做到这一点,你必须将它添加到每一个不同的管理模板)。因此,您最终会得到:
<div id="init"
ng-include="/Content/app/admin/templates/init.html"
ng-show="ss.display.init"
ng-controller="AdminController">
</div>
因此,最终您拥有相同数量的属性,您需要整个模板路径,并且其可读性降低。看看您现在所拥有的,很明显可以看到意图。
您还可以更进一步,并使其灵活地成为元素或属性
<admin-template
id="init"
ng-show="ss.display.init"
data-template-url="init.html">
</admin-template>
app.directive('adminTemplate', ['stateService', function (stateService) {
return {
restrict: 'EA',
templateUrl: function (elem, attrs) {
return "/Content/app/admin/templates/" + attrs.templateUrl;
},
link: function (scope, element, attrs) {
scope.stateService = stateService;
}
};
}]);
它可能似乎做得很少,但是我的感觉是,以前的开发人员已经重构了重复代码,以达到这个小指令。我认为这是因为它去除了样板,允许轻松重复使用,并在标记中很好地传达了意图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句