angularjs指令用于扩展html。这些都是先从ng- 前缀的特殊属性。我们将讨论以下指令:
ng-app - 该指令启动一个angularjs应用。
ng-init - 该指令初始化应用程序数据。
ng-model - 此指令定义的模型,该模型是变量在angularjs使用。
ng-repeat - 该指令将重复集合中的每个项目的html元素。
ng-app 指令启动一个angularjs应用。它定义根元素。它会自动初始化或启动加载包含angularjs应用程序的web页面的应用程序。它也被用来加载各种angularjs模块angularjs应用。在下面的例子中,我们定义默认angularjs应用使用div元素的ng-app 属性。
<div ng-app=""> ... </div>
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指令定义在angularjs应用中使用的模型/变量。在下面的例子中,我们定义了一个名为“name”的模型。
<div ng-app=""> ... <p>enter your name: <input type="text" ng-model="name"></p> </div>
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。输入姓名并看到以下结果。
