简体   繁体   中英

angular js directive post link can't access generated element id

I have this directive:

/*html, enclosed in a ng-repeat directive*/
<textarea name="alternativaHtml" id="questao_alternativa_{{$index}}" data-ng-model="alternativa.TextoHtml" data-ck-editor></textarea>

/*javascript*/
angular
    .module("fluxo_itens.directives")
    .directive('ckEditor', [function () {
            return {
                require: '?ngModel',
                link: {
                    "post": PostLink
                }
            };
        }]);

function PostLink($scope, elm, attr, ngModel) {
    var ck = CKEDITOR.replace(attr.id);

    ck.on('pasteState', function () {
        $scope.$apply(function () {
            ngModel.$setViewValue(ck.getData());
        });
    });

    ngModel.$render = function (value) {
        ck.setData(ngModel.$modelValue);
    };
}

the problem is that when CKEDITOR tries to create the editor instance, it can't find the element, which has its id property dinamycally generated.

Just guessing , but you can try this :

<textarea name="alternativaHtml" id="questao_alternativa_{{$index}}" data-ng-model="alternativa.TextoHtml" data-ck-editor editor-id="questao_alternativa_{{$index}}"></textarea>

Directive

angular
.module("fluxo_itens.directives")
.directive('ckEditor', [function () {
        return {
            scope : {
             'editorId' : '='
            }
            require: '?ngModel',
            link: {
                "post": PostLink
            }
        };
    }]);

PostLink

function PostLink($scope, elm, attr, ngModel) {
var ck = CKEDITOR.replace($scope.editorId);

ck.on('pasteState', function () {
    $scope.$apply(function () {
        ngModel.$setViewValue(ck.getData());
    });
});

ngModel.$render = function (value) {
    ck.setData(ngModel.$modelValue);
};
}

The problem was that CkEditor wasn't able to find the element because the id of the element was not set in the DOM. So I've relied on jQuery to set de element DOM property so the CkEditor can find the textarea. I've changed this in the PostLink function

var ck = CKEDITOR.replace(attr.id);

to this:

$(elm).attr("id", attr.id).prop("id", attr.id);
var ck = CKEDITOR.replace(elm[0].id);

Now everything works fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM