Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 component with ng-model

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> 
like image 443
Moussa Avatar asked Jun 20 '16 12:06

Moussa


People also ask

What is [( ngModel )] in angular?

Angular NgModel is an inbuilt directive that creates a FormControl instance from the domain model and binds it to a form control element. The ngmodel directive binds the value of HTML controls (input, select, textarea) to application data. We can merely achieve it in the component element and the HTML element both.

Can we use NG model for Div?

NgModel expects the bound element to have a value property, which div s don't have. That's why you get the No value accessor error. I don't know if the input event is supported on all browsers for contenteditable . You could always bind to some keyboard event instead.

What is the difference between ng model and data NG model?

For AngularJS there is no difference between ng-app and data-ng-app or ng-controller and data-ng-controller or ng-model and data-ng-model because while compiling HTML page, AngularJS strips data- or x- prefix. Find the URL for reference.


2 Answers

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' }; 
like image 53
jcubic Avatar answered Oct 09 '22 15:10

jcubic


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.

like image 35
masitko Avatar answered Oct 09 '22 14:10

masitko