2016-06-20 76 views
19

是否可以在組件中使用ng-model?我想用一個ng-model將一個範圍變量綁定到一個組件。我有plunkered my issue。我希望將組件my-input綁定到範圍userData.name中的變量。ng-model的角度1.5組件

我正在使用Angular JS 1.5.6組件,並且希望避免使用指令。

<body ng-controller="MyCtrl"> 
    <div class="container"> 
    <h2>My form with component</h2> 
    <form role="form"> 
     <div class="form-group"> 
     <label>First name</label> 
     <my-input placeholder="Enter first name" ng-model="userData.name"></my-input> 
     </div> 
    </form> 
    </div> 
</body> 

回答

13

我已經爲您修復了plunker

您的參數名稱必須與組件中的名稱相對應。你應該在你的組件中使用camelCased名字,並在你的模板中使用kebab。例如:

bindings: { 
     myPlaceholder: '@', 
     myModel:'=' 
    } 

<my-input my-placeholder="Enter first name" my-model="userData.firstName"> 

關於你提到的有關使用NG-模型的問題 - 你可以使用任何參數就在您的組件定義它。在這種情況下,參數的名稱應該是ngModel

+0

它的工作感謝名單了很多很細!我會有最後一個問題。請問,當你有一個由按鈕和輸入組件組成的表單組件時,如何綁定數據:請參閱這個新的[plunk](http://plnkr.co/edit/jLnrDeledkkJBLaKWKjZ) – Mouss

23

您可以使用此代碼:

function myInputController($scope) { 
    var self = this; 
    this.$onInit =() => { 
     this.ngModel.$render =() => { 
      self.model = self.ngModel.$viewValue; 
     }; 
     $scope.$watch(function() { return self.model; }, function(value) { 
      self.ngModel.$setViewValue(value); 
     }); 
    }; 
} 
module.component('myInput', { 
    require: { 
     ngModel: '^ngModel' 
    }, 
    template: '<input ng-model="vm.model"/>', 
    controller: myInputController, 
    controllerAs: 'vm' 
}; 
+0

關於this.ngModel未定義把它放在$ onInit鉤子裏而不是超時? – jzig

+0

@jzig是的,這就是我現在做的。我會更新答案。 – jcubic

+1

我認爲這是一個更好的解決方案,因爲它實際上使用ngModel。 NgModel對於一些用例如表單驗證是必需的。 – narduk