質問

I am using AceEditor JavaScript library in my project. I want to use it via an Angular service, not by calling new on it.

Instead of this inside my controller:

$scope.ace = new AceEditor('my-editor-div');

I have created a factory for a service:

myapp.factory('AceService', function() {

    this.init=function(name) {
        return new AceEditor(name);
    };

    return this;
});

Which I call in my controller like this:

$scope.ace = AceEditorService.init('my-editor-div');

Am I doing this the correct Angular way?

役に立ちましたか?

解決

You can use 3rd party directives like http://angular-ui.github.io/ui-ace/

Or alternatively you can easily wrap Ace editor with angular directive like this:

YOUR_MODULE.directive("ace",[function() {
return {
    restrict : 'EA',
    require : '?ngModel',
    replace:true,
    template:"<div></div>",
    scope:{
    },
    link : function(scope, elem, attrs, ngModel) {
        if(!ngModel) 
            return;

        //bind ace editor to editor attribute
        scope.$watch('ace', function() {
            if(attrs.editor)
                scope.$eval('$parent.'+attrs.editor + ' = ace');
        });


        var html = elem.html();
        var editor = ace.edit(elem[0]);

        //some default settings
        editor.setTheme("ace/theme/chrome");
        editor.getSession().setMode(attrs.mode ? "ace/mode/"+attrs.mode : "ace/mode/javascript");
        attrs.$observe("mode",function(v){
            if(v){
                editor.getSession().setMode("ace/mode/"+attrs.mode);
            }
        });

        editor.resize();
        editor.setValue(html);
        editor.clearSelection();
        editor.moveCursorTo(0, 0);

        scope.ace = editor;

        //specify how UI should be updated
        ngModel.$render = function() {
            editor.setValue(ngModel.$viewValue);
        };

        function valid(editor) {
            return (Object.keys(editor.getSession()
                    .getAnnotations()).length == 0);
        }
        editor.on('change', function() {
            ngModel.$setViewValue(editor.getValue());
        });
    }
};
}]);

And then call it in your html like this:

<ace ng-model="some_value" mode="xml"></ace>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top