2017-03-06 196 views
0

我的应用程序的目标是创建属性编辑器。从服务器我得到的属性列表,它的类型:动态属性AngularJS

$scope.properties = [ 
    {name: 'property1', type: 'integer', 'value': 123}, 
    {name: 'property2', type: 'bool', 'value': 123}, 
    {name: 'property3', type: 'string', 'value': 123}, 
    {name: 'property4', type: 'custom', 'value': 123}, 
]; 

使用这些数据我想创建HTML列表这样。 这部分不起作用。如何改变它?

<ul> 
    <li ng-repeat="property in properties"> 
     <div property-editor-{{property.name}} my-data="property"></div> 
    </li> 
</ul> 

那么我可以很容易地实现与指令是这样的

angular.module('PropertyEditor').directive('propertyEditorCustom', function() { 
    return {restrict: 'A',controller:function(){...}}; 
}) 

PS定制控制器:我想避免一个集中的开关,因为新的模块可以增加它的自定义类型。

回答

1

它不会像这样工作。或者你需要第一个指令来绑定第二个动态指令。

我更好的建议使用值:

<ul> 
    <li ng-repeat="property in properties"> 
     <div property-editor="property.name" my-data="property"></div> 
    </li> 
</ul> 

,并得到它是这样的:

angular.module('PropertyEditor').directive('propertyEditor', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      propertyEditor: '=' 
     }, 
     controller: ['$scope', function($scope) { 
      console.log($scope.propertyEditor); // Here you can do specific stuff for propertyEditor 
     }] 
    }; 
}) 

要绑定与它第二个指令(我真的不推荐使用),您可以使用链接:

angular.module('PropertyEditor').directive('propertyEditor', ['$compile', function($compile) { 
    return { 
     restrict: 'A', 
     scope: { 
      propertyEditor: '=' 
     }, 
     link: function($scope, $element) { 
      var $newElement = $element.clone(true); 
      $newElement.removeAttr('property-editor').attr('property-editor-' + $scope.propertyEditor, 'property-editor-' + $scope.propertyEditor); 
      $handler = $('<div>').append($newElement); 
      $element.replaceWith($compile($handler.html())($scope)); 
     } 
    }; 
}]) 
+0

谢谢,我怎么能得到动态指令使用这个帮手吗?指令控制器(propertyEditor)可以创建这个吗?

+0

你说**链接**不建议使用,你能解释一下原因吗?有推荐的解决方案吗?或者我应该改变我的态度 –

+0

是的,动态重新编译,重新传输或者像在动态重新创建DOM等任何东西都会使您的代码非常难以维护。为什么不使用一个**属性编辑器**来处理每种属性的类型参数? – KyleK