目录

AngularJS - 指令( Directives)

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

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

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

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

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

ng-app directive

ng-app指令启动AngularJS应用程序。 它定义了根元素。 当加载包含AngularJS Application的网页时,它会自动初始化或引导应用程序。 它还用于在AngularJS Application中加载各种AngularJS模块。 在以下示例中,我们使用

元素的ng-app属性定义默认的AngularJS应用程序。
<div ng-app = "">
   ...
</div>

ng-init directive

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 directive

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>

例子 (Example)

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

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>

输出 (Output)

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

新页面打开
↑回到顶部↑
WIKI教程 @2018