Why does AngularJS ng-view not work locally?

后端 未结 3 424
粉色の甜心
粉色の甜心 2020-12-05 02:55

I have been working for a few hours on getting my links to click through to different views with my AngularJS app.

However, I can only seem to get the functionality

相关标签:
3条回答
  • 2020-12-05 03:32

    ng-view will work locally if you put your templates inside index.html itself instead of putting in separate files using script tags, so that angular will no longer need to make AJAX requests to fetch them.

    <script type="text/ng-template" id="home.html">
      This is the Home template
    </script>
    
    0 讨论(0)
  • 2020-12-05 03:45

    Both ng-view and ng-include use AJAX to load templates. The problem is that browser by default does not allow AJAX requests to files located on your local file system (for security reasons). Therefore you have two options:

    1. Run local web server that will serve your files
    2. Tell your browser to allow local files access

    If you are on Mac, the fist option is rather easy since you have several built-in web servers (Apache httpd and Python module called SimpleHTTPServer). To run Python SimpleHTTPServer module just open console in the folder your files located at and run

    python -m SimpleHTTPServer 3000
    

    then open your browser and type http://localhost:3000. That's it.

    If you are on Windows, it's also possible. You can install for example Wamp and serve files from it.

    Second option is possible with Chrome, just run it with --allow-file-access-from-files option from command line or add this flag to shortcut after path to Chrome executable.

    This resource may also be useful to understand how to run things locally in different browsers and using different web servers.

    0 讨论(0)
  • 2020-12-05 03:47

    ng-view and ng-include make ajax requests to serve the template file. Because you're running it locally, it can't make that request. An easy fix around this is to use http-server to serve your contents over a local server.

    0 讨论(0)
提交回复
热议问题