天天看點

AngularJS擷取getElementById()不起作用及HTML與controller加載順序問題

AngularJS項目需要引入富文本插件,富文本插件需要擷取HTMLdom的id進行富文本插件初始化,是以最開始采用getElementById()方法想要擷取id,但是console報出擷取不到id,寫法如下:

define(["app", "wangEditor"], function (app, E) {
    app.controller("savingEdit", ["$scope", "$rootScope",'$timeout',
        function ($scope, $rootScope,$timeout) {
            //富文本編輯器,引入wangEditor組建,并初始化
            var editeditor;
            $scope.myEditorClick = function () {
                //初始化E
                editeditor = new E(document.getElementById("myEditEditor"));
                //渲染富文本編輯器
                editeditor.create();
            }
            $scope.myEditorClick();
        }
    ]);
});
           
<div id="myEditEditor"></div>
           

上面這種寫法會報myEditEditor為空id。

經過分析,我推測是因為AngularJS在加載controller時,對應的HTML檔案并沒有加載完成,他們可能是同時加載的。在網上搜尋了很多辦法,最後我總結出如下兩種辦法實作id的正常擷取:

1.$timeout延時處理

這個辦法顯而易見,既然直接加載擷取不到,那就價格延時,等html加載了在執行js渲染。代碼如下:

define(["app", "wangEditor"], function (app, E) {
    app.controller("savingEdit", ["$scope", "$rootScope",'$timeout',
        function ($scope, $rootScope,$timeout) {
            //富文本編輯器,引入wangEditor組建,并初始化
            var editeditor;
            $scope.myEditorClick = function () {
                //初始化E
                editeditor = new E(document.getElementById("myEditEditor"));
                //渲染富文本編輯器
                editeditor.create();
            }
            $timeout(function () {
                $scope.myEditorClick();
            },300);
        }
    ]);
});
           
<div id="myEditEditor"></div>
           

2.通過directive監聽html文本是否渲染完成

大家一般是監聽ng-repeat是否渲染完最後一條來監聽,你也可以監聽其他html是否渲染完成。以ng-repeat為例,代碼如下:

app.directive('repeatFinish',function(){
    return {
        link: function(scope,element,attr){
            console.log(scope.$index)
            if(scope.$last == true){
                scope.$eval( attr.repeatFinish )
            }
        }
    }
})
           
<div id="box">
    <span ng-repeat="item in data" repeat-finish="renderFinish()">{{item.str}}</span>
</div>