AngularJS 指令
时间:2021-11-22 作者:匿名
AngularJS指令用于扩展HTML。 他们是特殊的属性入手ng前缀。 让我们讨论以下指令−
ng-app−这个指令AngularJS应用程序开始。
ng-init−这个指令初始化应用程序数据。
ng-model−这个指令定义了模型变量用于AngularJS。
ng-repeat−这个指令重复中每一项的HTML元素的集合。
ng-app指令
ng-app指令AngularJS应用程序开始。 它定义了根元素。 它自动初始化或正常应用程序时,web页面包含AngularJS加载应用程序。 它还可以用于在AngularJS应用程序加载各种AngularJS模块。 在接下来的例子中,我们定义了一个默认使用ng-app AngularJS应用程序属性的< div >元素。
<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应用程序。 在接下来的例子中,我们定义了一个模型命名的名字.
<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://www.yangzhiw.cn/static/js/angularjs-1.82/angular.min.js"> </script> </body> </html>
输出
打开文件testAngularJS.htm在一个web浏览器。 输入您的名字并看到结果。