Javascript not accessible from inside Angular ui-view

前端 未结 7 1652
执念已碎
执念已碎 2021-01-18 17:56

I have a main template (index.html) with an Angular ui-view. Inside this main template I import a bunch of Javascript files. I expect these files to be available to the cont

7条回答
  •  长情又很酷
    2021-01-18 18:35

    Presumably, you have a statement somewhere in app.js that looks like this:

    angular.module('MyApp', []);
    

    You will need to manually bootstrap your application. If you have any ng-app= markup in your html, remove it -- make sure app.js is the very last script, and add the following to the end of app.js:

    angular.element(document).ready(function() {
      angular.bootstrap(document, ['MyApp']);
    });
    

    If you didn't have ng-app in your markup, then you wouldn't have seen anything anyway, as ng-app is the key that tells angular where it should integrate with your page. And ng-app should not be applied until all of the scripts are loaded.

    But even if you had it, it still would have given you an error that the directive is not defined. The reason is that angular.js will begin executing as soon as it is loaded. But the code you've written which attaches the directive to your module has not gotten a chance to execute. Very specifically, it means that there is not yet a directive called 'ui-view' defined in your application.

    The reason angular code seems to just work when you put it into index.html is that angular is kind enough to wait for the DOM to be ready before actually trying to hook up components, and that means that any inline scripts have already gotten a chance to execute.

    Keep this bootstrapping trick in your bag, as you'll be using it often.

提交回复
热议问题