Angular 1.5 component with ng-model

All we need is an easy explanation of the problem, so here it is.

Is it possible to use ng-model with a component? I would like to bind a scope variable to a component with ng-model. I have plunkered my issue. I would like the component my-input to be binded to the variable from the scope userData.name.

I am using Angular JS 1.5.6 components, and want to avoid using directive.

<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>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can use this code:

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'
};

Method 2

I’ve fixed the plunker for you.

Names of you parameters have to correspond to the names in your component. You should be using camelCased names in your component and kebab-cased in your templates. Example:

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

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

Regarding your question about using ng-model – you can use any parameter as far you define it in your component. In this case the name of your parameter should be ngModel.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply