2015-03-31 22 views
1

假設我有一些看起來像這樣:現有元素上綁定一個新ngModel

<input ng-model="object.properties.property_name" options="{ updateOn: 'blur' }" ng-change="object.save('property_name')"> 

我想那,而不是真正的短這樣的:

<input name="property_name" autosave="object"> 

但要做到這一點我需要將ngModel動態綁定到現有的輸入。我已經縮短了它迄今爲止是這樣的:

<input ng-model="object.properties.property_name" name="property_name" autosave="object"> 

而這正是讓我那麼遠的指令:

.directive('autosave', [function() { 
    return { 
     restrict: 'A', 
     scope : { 
      autosave : '=', 
     }, 
     link: function(scope, element, attrs) { 
      element.bind('change', function(){ 
       scope.autosave.save(attrs.name); 
      }); 
     } 
    } 
}]) 

如何動態地添加scope.autosave.properties[attrs.name]到ngModel,並將其綁定到輸入標籤?

+0

我應該指出,我不能替換輸入標籤,因爲自動保存可以很容易地應用於textarea或選擇列表。 – 2015-03-31 18:00:22

回答

0

我還沒有找到一種方式來創建一個模型,這是原來的問題,但我已通過從模型像這樣拉屬性名短:

<input ng-model="object.properties.property_name" autosave="object"> 

和這個指令

.directive('autosave', [function() { 
    return { 
     restrict: 'A', 
     scope : { 
      autosave : '=', 
     }, 
     link: function(scope, element, attrs) { 
      element.bind('change', function(){ 
       var property_name = attrs.ngModel.match(/(?=[^.]*$)(\w+)/)[1]; 
       scope.autosave.save(property_name); 
      }); 
     } 
    } 
}]) 

這並不理想,但它更好。