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