AngularJS指令用于扩展HTML。这些都是先从ng- 前缀的特殊属性。我们将讨论以下指令:
ng-app指令
ng-app 指令启动一个AngularJS应用。它定义根元素。它会自动初始化或启动加载包含AngularJS应用程序的Web页面的应用程序。它也被用来加载各种AngularJS模块AngularJS应用。在下面的例子中,我们定义默认AngularJS应用使用div元素的ng-app 属性。
<div ng-app=\"\"> ... </div>
ng-init 指令
ng-init 指令初始化一个AngularJS应用程序的数据。它被用来把值在应用程序中使用的变量。在下面的例子中,我们将初始化countries数组。使用JSON语法来定义countries数组。
<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元素集合中的每个项目。在下面的例子中,我们已经迭代了数组countries。
<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.html
<html> <title>AngularJS Directives</title> <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=\"http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js\"></script> </body> </html>
输出
在Web浏览器打开textAngularJS.html。输入姓名并看到以下结果。
本文地址:https://www.stayed.cn/item/18158
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我