Created
February 23, 2017 10:32
-
-
Save jens1101/da13d28a5e8ce97f491bcb216b72c1de to your computer and use it in GitHub Desktop.
ngModel Cheatsheet. How to interact with ngModel via JavaScript in your own Angular components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var app = angular.module('example', []); | |
| app.component('foo', { | |
| require: { | |
| theModel: '^ngModel' | |
| }, | |
| template: '[...]', | |
| controller: FooCtrl, | |
| bindings: { | |
| options: '<' | |
| } | |
| }); | |
| function FooCtrl() { | |
| //From here you can access the required directives and the bindigns directly on the controller's scope | |
| this.theModel !== undefined; //This is ngModel that was required | |
| this.options !== undefined; //This is the binded variable from bindings | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var app = angular.module('example', []); | |
| app.component('foo', { | |
| require: { | |
| ngModel: '^ngModel' | |
| }, | |
| template: '[...]', | |
| controller: FooCtrl, | |
| bindings: {} | |
| }); | |
| function FooCtrl() { | |
| var $ctrl = this; | |
| var value; | |
| $ctrl.$onInit = function () { | |
| //Get the current ngModel value | |
| value = $ctrl.ngModel.$modelValue; | |
| //Run this function each time the ngModel value was changed **externally** | |
| $ctrl.ngModel.$render = function () { | |
| value = $ctrl.ngModel.$modelValue; | |
| }; | |
| }; | |
| $ctrl.setValue(val) { | |
| value = val; | |
| //Set the ngModel value | |
| $ctrl.ngModel.$setViewValue(event.value.newValue); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment