Skip to content
This repository was archived by the owner on May 25, 2019. It is now read-only.

Made ui-codemirror work with updateOn: 'blur' #104

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion src/ui-codemirror.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ angular.module('ui.codemirror', [])
/**
* @ngInject
*/
function uiCodemirrorDirective($timeout, uiCodemirrorConfig) {
function uiCodemirrorDirective($timeout, $rootScope, uiCodemirrorConfig) {

return {
restrict: 'EA',
Expand Down Expand Up @@ -132,6 +132,28 @@ function uiCodemirrorDirective($timeout, uiCodemirrorConfig) {
});
}
});

// Commit as with NgModelController
codemirror.on('blur', function() {
if (ngModel.$touched) {
return;
}

if ($rootScope.$$phase) {
scope.$evalAsync(ngModel.$setTouched);
} else {
scope.$apply(ngModel.$setTouched);
}
});

// Debounce as with NgModelController
if (ngModel.$options && ngModel.$options.updateOn) {
ngModel.$options.updateOn.split(/\s+/).forEach(function(trigger) {
codemirror.on(trigger, function() {
ngModel.$$debounceViewValueCommit(trigger);
});
});
}
}

function configUiRefreshAttribute(codeMirror, uiRefreshAttr, scope) {
Expand Down
29 changes: 29 additions & 0 deletions test/codemirror.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ describe('uiCodemirror', function() {
return codemirror;
});

window.CodeMirror.signal = _constructor.signal;
window.CodeMirror.defaults = codemirrorDefaults;
});

Expand Down Expand Up @@ -274,6 +275,34 @@ describe('uiCodemirror', function() {

});

it('when the IDE changes should update the model on blur', function() {
// Define values
var oldValue = 'bar';
var newValue = 'baz';

// Create codemirror editor and bind with updateOn blur
var element = $compile('<div ui-codemirror ng-model="foo" ng-model-options="{updateOn: \'blur\'}"></div>')(scope);
var ctrl = element.controller('ngModel');

// Check initial states
expect(ctrl.$pristine).toBe(true);
expect(ctrl.$valid).toBe(true);
scope.$apply('foo = "' + oldValue + '"');
expect(scope.foo).toBe(oldValue);
expect(codemirror.getValue()).toBe(oldValue);

// Change text but DO NOT blur
codemirror.setValue(newValue);
expect(scope.foo).toBe(oldValue);
expect(codemirror.getValue()).toBe(newValue);

// Blur and observe change to model
window.CodeMirror.signal(codemirror, 'blur', codemirror);
expect(scope.foo).toBe(newValue);
expect(ctrl.$valid).toBe(true);
expect(ctrl.$dirty).toBe(true);
});

it('when the model changes should update the IDE', function() {
var element = $compile('<div ui-codemirror ng-model="foo"></div>')(scope);
var ctrl = element.controller('ngModel');
Expand Down