2016-11-17 33 views
0

我有一個ng格式的組件。我想動態地設置ng表單的名稱,這樣我就可以輕鬆地訪問組件的ng元素值。如何設置ng格式的動態名稱

例子:

<form name="formName"> 
<component name="componentName"></component> 
</form> 

和組件裏面我有

<ng-form name="{{$ctrl.name}}"> 
// Some inputs with special validation 
</ng-form> 

但每次我試圖在我的部分是不確定的,或只是一個字符串而不是訪問$ ctrl.name形式與內部輸入。

我用的打字稿:

@Component(app, { 
    selector: 'component', 
    templateUrl: 'templateUrl', 
    bindings: { 
    value: '=?ngModel', 
    name: '@', 
    required: '=?ngRequired', 
    disabled: '=?ngDisabled', 

    }, 
}) 
    console.log(this.name); ///A string, but no a form so I can manipulate it. 

回答

1

請嘗試以下示例代碼

Component.js

angular.module('myApp').component('component', { 
    bindings: {    
     name: '@' 
    }, 
    template: 
    '<ng-form name={{$ctrl.name}}><input name="txtfirst" value="John"/><input type="button" ng-click="$ctrl.getFormData()"></ng-form>', 
    controller: function($scope) { 
     console.log(this.name); 

    this.getFormData = function(){ 
      console.log($scope[this.name]); 
    }   
    } 
}); 

HTML

<component name="frmNameTest"></component> 
+0

是的,代碼工作,但不是我想要的。我獲得一個帶有表單名稱的字符串,我希望表單對象具有一個動態名稱,這樣我可以在控制器內部進行操作。 –

+1

請檢查更新的代碼。 「$ scope [this.name]」會給出表單對象。 –

+0

這在窗體上工作,但我想在NG-FORM中使用,我不知道如何正確使用。 –

1

如果你想在表單對象是可用Ø控制器,而不是範圍,那麼你可以這樣做,除了表格聲明是

<form name="$ctrl[{{$ctrl.name}}]"> 
    ... 
</form>