1+ 'use strict' ;
2+ angular . module ( 'ui.codemirror' , [ ] ) . constant ( 'uiCodemirrorConfig' , { } ) . directive ( 'uiCodemirror' , [
3+ 'uiCodemirrorConfig' ,
4+ function ( uiCodemirrorConfig ) {
5+ return {
6+ restrict : 'EA' ,
7+ require : '?ngModel' ,
8+ priority : 1 ,
9+ compile : function compile ( tElement ) {
10+ if ( angular . isUndefined ( window . CodeMirror ) ) {
11+ throw new Error ( 'ui-codemirror need CodeMirror to work... (o rly?)' ) ;
12+ }
13+ var value = tElement . text ( ) ;
14+ var codeMirror = new window . CodeMirror ( function ( cm_el ) {
15+ angular . forEach ( tElement . prop ( 'attributes' ) , function ( a ) {
16+ if ( a . name === 'ui-codemirror' ) {
17+ cm_el . setAttribute ( 'ui-codemirror-opts' , a . textContent ) ;
18+ } else {
19+ cm_el . setAttribute ( a . name , a . textContent ) ;
20+ }
21+ } ) ;
22+ if ( tElement . parent ( ) . length <= 0 ) {
23+ tElement . wrap ( '<div>' ) ;
24+ }
25+ tElement . replaceWith ( cm_el ) ;
26+ } , { value : value } ) ;
27+ return function postLink ( scope , iElement , iAttrs , ngModel ) {
28+ var options , opts ;
29+ options = uiCodemirrorConfig . codemirror || { } ;
30+ opts = angular . extend ( { } , options , scope . $eval ( iAttrs . uiCodemirror ) , scope . $eval ( iAttrs . uiCodemirrorOpts ) ) ;
31+ function updateOptions ( newValues ) {
32+ for ( var key in newValues ) {
33+ if ( newValues . hasOwnProperty ( key ) ) {
34+ codeMirror . setOption ( key , newValues [ key ] ) ;
35+ }
36+ }
37+ }
38+ updateOptions ( opts ) ;
39+ if ( angular . isDefined ( scope . $eval ( iAttrs . uiCodemirror ) ) ) {
40+ scope . $watch ( iAttrs . uiCodemirror , updateOptions , true ) ;
41+ }
42+ codeMirror . on ( 'change' , function ( instance ) {
43+ var newValue = instance . getValue ( ) ;
44+ if ( ngModel && newValue !== ngModel . $viewValue ) {
45+ ngModel . $setViewValue ( newValue ) ;
46+ }
47+ if ( ! scope . $$phase && ! scope . $root . $$phase ) {
48+ scope . $apply ( ) ;
49+ }
50+ } ) ;
51+ if ( ngModel ) {
52+ ngModel . $formatters . push ( function ( value ) {
53+ if ( angular . isUndefined ( value ) || value === null ) {
54+ return '' ;
55+ } else if ( angular . isObject ( value ) || angular . isArray ( value ) ) {
56+ throw new Error ( 'ui-codemirror cannot use an object or an array as a model' ) ;
57+ }
58+ return value ;
59+ } ) ;
60+ ngModel . $render = function ( ) {
61+ var safeViewValue = ngModel . $viewValue || '' ;
62+ codeMirror . setValue ( safeViewValue ) ;
63+ } ;
64+ }
65+ if ( iAttrs . uiRefresh ) {
66+ scope . $watch ( iAttrs . uiRefresh , function ( newVal , oldVal ) {
67+ if ( newVal !== oldVal ) {
68+ codeMirror . refresh ( ) ;
69+ }
70+ } ) ;
71+ }
72+ if ( angular . isFunction ( opts . onLoad ) ) {
73+ opts . onLoad ( codeMirror ) ;
74+ }
75+ } ;
76+ }
77+ } ;
78+ }
79+ ] ) ;
0 commit comments