簡體   English   中英

angular js的執行順序

[英]angular js order of execution

我是angular的新手,正在嘗試在一個js文件中定義模塊,並且我覺得angular正在立即處理我的dom,其中var app = angular.module("myApp", []); 將在以后在Shell或其模塊之一中定義。

我嘗試使用常規腳本標記,但是有錯誤,並且我假設一旦我的dom准備好后再注入它,然后在Shell實例化模塊,就可以了。 請指導。

使用Javascript

document.addEventListener("DOMContentLoaded", function(event) {
     inject();
     new Shell();
});

function inject() {
    var ng = document.createElement('script');
    ng.src = "js/api/angular.js";
    var scripts = document.getElementsByTagName('script')[0]; 
    scripts.parentNode.insertBefore(ng, scripts);
}

內殼

var app = angular.module("myApp", []);
        app.controller("MyController", function($scope) {
            $scope.author = {
                "name": "My name",
                "title": "Developer",
                "company": "my company"
            }
        });

我的HTML是

 <div id="result" ng-app="myApp">
        <div ng-controller="MyController">
            <h1>{{author.name}}</h1>
            <p>{{author.title + ", " + author.company}}</p>
        </div>
    </div>

我應該如何解決這個問題,即在我讓我定義模塊之前,請稍等一下。

問題在於,angular還會偵聽DOMContentLoaded ,一旦被觸發,它會尋找名為myApp模塊,因為您在ng-app="myApp"指令中指定了它。 如果要更改此行為,則應自行引導角度。 在您的情況下,您需要從div刪除ng-app="myApp"並添加angular.bootstrap(..., ['myApp']); 在定義模塊並定義所有服務,指令,控制器和其他與模塊相關的東西之后,將其添加到Shell()構造函數中,因為在引導模塊之后,您將無法再執行該操作。

HTML

<div id="result" ng-cloak> 
    ...
</div>

貝殼

var app = angular.module("myApp", []);
    app.controller("MyController", function($scope) {
      ...
    });

// <= Define here all module related stuff

angular.bootstrap(document.getElementById('result'), ['myApp']);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM