AngularJS - 指令

AngularJS指令用于扩展HTML.它们是以 ng -prefix开头的特殊属性.让我们讨论以下指令 :

  • ng-app : 该指令启动AngularJS应用程序.

  • ng-init : 该指令初始化应用程序数据.

  • ng-model : 该指令定义了可在AngularJS中使用的变量模型.

  • ng-repeat : 该指令为集合中的每个项重复HTML元素.

ng-app指令

ng-app指令启动AngularJS应用程序.它定义了根元素.当加载包含AngularJS Application的网页时,它会自动初始化或引导应用程序.它还用于在AngularJS Application中加载各种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 directive

ng-model指令定义要在AngularJS Application中使用的模型/变量.在以下示例中,我们定义名为 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>

输出

在Web浏览器中打开文件 testAngularJS.htm .输入你的名字并查看结果.