AngularJS教程

AngularJS 指令

AngularJS 指令用于扩展 HTML。它们是以 ng 前缀开头的特殊属性。让我们讨论以下指令-
ng-app-该指令启动一个 AngularJS 应用程序。 ng-init-该指令初始化应用程序数据。 ng-model-该指令定义了要在 AngularJS 中使用的变量模型。 ng-repeat-该指令为集合中的每个项目重复 HTML 元素。

ng-app 指令

ng-app 指令启动一个 AngularJS 应用程序。它定义了根元素。当包含 AngularJS 应用程序的网页被加载时,它会自动初始化或引导应用程序。它还用于在 AngularJS 应用程序中加载各种 AngularJS 模块。在以下示例中,我们使用 <div> 元素的 ng-app 属性定义了一个默认的 AngularJS 应用程序。
<div ng-app = "">
   ...
</div>

ng-init 指令

ng-init 指令初始化一个 AngularJS 应用程序数据。它用于为变量赋值。在下面的例子中,我们初始化了一个国家数组。我们使用 JSON 语法来定义国家/地区数组。
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, 
   {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
   ...
</div>

ng-model 指令

ng-model 指令定义了要在 AngularJS 应用程序中使用的模型/变量。在下面的例子中,我们定义了一个名为 name 的模型。
<div ng-app = "">
   ...
   <p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>

ng-repeat 指令

ng-repeat 指令为集合中的每个项目重复 HTML 元素。在以下示例中,我们遍历国家/地区数组。
<div ng-app = "">
   ...
   <p>List of Countries with locale:</p>
   
   <ol>
      <li ng-repeat = "country in countries">
         {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
      </li>
   </ol>
</div>

示例

以下示例显示了上述所有指令的使用。

testAngularJS.htm

<html>
   <head>
      <title>AngularJS Directives</title>
   </head>
   
   <body>
      <h1>Sample Application</h1>
      
      <div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, 
         {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]"> 
         <p>Enter your Name: <input type = "text" ng-model = "name"></p>
         <p>Hello <span ng-bind = "name"></span>!</p>
         <p>List of Countries with locale:</p>
      
         <ol>
            <li ng-repeat = "country in countries">
               {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
            </li>
         </ol>
      </div>
      
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      
   </body>
</html>
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4