From 1d469462fc5824152389134b969fa95edcf14795 Mon Sep 17 00:00:00 2001 From: Jeremy Ebler Date: Mon, 28 Apr 2014 19:04:30 -0700 Subject: [PATCH] Only hook codeMirror change event if using ngModel, use scope.$apply correctly (wrap code in apply, not call apply after) --- src/ui-codemirror.js | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/ui-codemirror.js b/src/ui-codemirror.js index a9c3153..ce73775 100644 --- a/src/ui-codemirror.js +++ b/src/ui-codemirror.js @@ -61,16 +61,6 @@ angular.module('ui.codemirror', []) if (angular.isDefined(scope.$eval(iAttrs.uiCodemirror))) { scope.$watch(iAttrs.uiCodemirror, updateOptions, true); } - // Specialize change event - codeMirror.on('change', function (instance) { - var newValue = instance.getValue(); - if (ngModel && newValue !== ngModel.$viewValue) { - ngModel.$setViewValue(newValue); - } - if (!scope.$$phase) { - scope.$apply(); - } - }); if (ngModel) { @@ -95,6 +85,18 @@ angular.module('ui.codemirror', []) var safeViewValue = ngModel.$viewValue || ''; codeMirror.setValue(safeViewValue); }; + + + // Keep the ngModel in sync with changes from CodeMirror + codeMirror.on('change', function (instance) { + var newValue = instance.getValue(); + if (newValue !== ngModel.$viewValue) { + // Changes to the model from a callback need to be wrapped in $apply or angular will not notice them + scope.$apply(function() { + ngModel.$setViewValue(newValue); + }); + } + }); }