AngularJS 指令


AngularJS 指令用于扩展 HTML。它们是特殊属性,以 ng -字首。让我们讨论以下指令:

  • ng-app :这个指令启动一个AngularJS应用程序。

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

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

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

ng-app 指令


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

元素的 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>

例子


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

测试AngularJS.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>

打开文件 测试AngularJS.htm 在网络浏览器中。输入你的姓名并查看结果。