我正在使用服务器端生成的JSON使用Angular 1.2.29的不同指令填充自定义视图。考虑到性能和良好做法,我有几个问题要问,这样做的正确方法是什么。
function processItems(items) { angular.forEach(items, function(item) { switch(item.type) { case 'directive1': var newDirective = angular.element('<directive-one></directive-one>'); newDirective.attr('value', item.value); var compiledHtml = $compile(newDirective)(scope); element.append(compiledHtml); break; case 'directive2': var newDirective = angular.element('<directive-two></directive-two>'); newDirective.attr('value', item.value); var compiledHtml = $compile(newDirective)(scope); element.append(compiledHtml); break; } }) }
我创建了一个Plunker,向大家展示我目前的方法。欢迎评论和回答!https://plnkr.co/edit/Za4ANluUkXYP5RCcnuAb?p=preview
在生成动态过滤器类型功能时,我已经经历过很多次此问题。您的代码有效,但我认为这是过度设计的,而且可读性很差。不需要GenericItems指令。我将尝试将功能移至视图,并明确说明类型更改时会发生什么。这是我作为柱塞的解决方案
控制器
<div ng-controller="appCtrl as app">
<p>{{app.name}}</p>
<button ng-click="app.add1()">Directive 1</button>
<button ng-click="app.add2()">Directive 2</button>
<button ng-click="app.remove()">Remove</button>
<div ng-repeat="item in app.items">
<directive-one value="item.value" ng-if="item.type==='directive1'"></directive-one>
<directive-two value="item.value" ng-if="item.type==='directive2'"></directive-two>
</div>
</div>
app.js
app.controller('appCtrl', function() {
var vm = this;
vm.items = [];
vm.name = 'Dynamic directive test';
vm.add1 = function() {
vm.items.push({type: 'directive1', value: Math.random()})
};
vm.add2 = function() {
vm.items.push({type: 'directive2', value: Math.random()})
};
vm.remove = function() {
vm.items.pop();
};
});
app.directive('directiveOne', function() {
return {
scope: {
value: '='
},
restrict: 'E',
template: '<p>d1: {{value}}</p>'
}
});
app.directive('directiveTwo', function() {
return {
scope: {
value: '='
},
restrict: 'E',
template: '<p>d2: {{value}}</p>'
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句