Skip to content

Instantly share code, notes, and snippets.

@jens1101
Created February 23, 2017 10:32
Show Gist options
  • Select an option

  • Save jens1101/da13d28a5e8ce97f491bcb216b72c1de to your computer and use it in GitHub Desktop.

Select an option

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