How to combine angularjs and xhtml?

后端 未结 2 1101
遇见更好的自我
遇见更好的自我 2021-02-06 08:50

Here is an example of a minimal example for angularjs which works when saved as angular.html:



        
相关标签:
2条回答
  • 2021-02-06 09:20

    I found a solution using manual setup. The code then looks like this:

    <!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <title>My HTML File</title>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js" />
        <script type="text/javascript">
            angular.module('myApp', []);
    
        angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
        });
      </script>
    </head>
    <body>
    
      <p>Nothing here {{'yet' + '!'}}</p>
    
    </body>
    </html>
    

    While this seems a suitable workaround for now, I'd still love to know what the problem is...

    0 讨论(0)
  • 2021-02-06 09:25

    One of the best ways to do this is to use the HTML/XHTML data- attributes. You can write valid HTML and XHTML without having to include any angular namespace. This would be as follows:

    <!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" data-ng-app="">
    <head>
      <title>My HTML File</title>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js" />
    </head>
    <body>
    
      <p>Nothing here {{'yet' + '!'}}</p>
    
    </body>
    </html>
    

    This is also beneficial when it comes to all other Angular declarations, such as ng-repeat and ng-show, etc.

    <div ng-repeat="item in items">{{item.name}}</div> // This won't validate.
    <div data-ng-repeat="item in items">{{item.name}}</div> // This will validate.
    

    Note that your solution with bootstrapping the Angular app is also valid - but it's not really a fix for the issue you're having. (It's simply a different way to load your Angular app, which happened to work for your situation since you didn't have any other ng- directives in your markup.)

    See a similar question and answer here.

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