AngularJS 指令是扩展的 HTML 属性,带有前缀 ng-。
比如:
ng-app 指令初始化一个 AngularJS 应用程序。
ng-init 指令初始化应用程序数据。
这个在之前已经说过了,下面讲一下之前没讲到的。
ng-repeat指令与ng-options指令
<!--一般ng-repeat通常用于ul与li这种列表和表格--><div ng-app="" ng-init="names=[{name:'Jani',country:'Norway'},{name:'Hege',country:'Sweden'},{name:'Kai',country:'Denmark'}]"><p>循环对象:</p><ul> <li ng-repeat="x in names"> {{ x.name + ', ' + x.country }} </li></ul></div>
<!--一般ng-options通常用于select这种下拉框--><select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars"></select><h1>你选择的是: {{selectedCar.brand}}</h1><h2>模型: {{selectedCar.model}}</h2><h3>颜色: {{selectedCar.color}}</h3><p>下拉列表中的选项也可以是对象的属性。</p></div><script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = { car01 : {brand : "Ford", model : "Mustang", color : "red"}, car02 : {brand : "Fiat", model : "500", color : "white"}, car03 : {brand : "Volvo", model : "XC90", color : "black"} }});</script>
当然用ng-repeat也可以实现下拉框。
<select ng-model="selectedSite"><option ng-repeat="x in sites" value="{{x.site}}">{{x.site}}</option></select>
ng-model 指令
利用ng-model指令不仅可以双向绑定控件到AngularJS应用程序的变量,还可以用来验证数据有效性
<form ng-app="" name="myForm"> Email: <input type="email" name="myAddress" ng-model="text"> <span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span></form>
提示信息会在 ng-show
属性返回 true
的情况下显示。
ng-model
指令可以为应用数据提供状态值(invalid, dirty, touched, error):
<form ng-app="" name="myForm" ng-init="myText = 'test@qq.com'"> Email: <input type="email" name="myAddress" ng-model="myText" required> <p>编辑邮箱地址,查看状态的改变。</p> <h1>状态</h1> <p>Valid: {{myForm.myAddress.$valid}} (如果输入的值是合法的则为 true)。</p> <p>Dirty: {{myForm.myAddress.$dirty}} (如果值改变则为 true)。</p> <p>Touched: {{myForm.myAddress.$touched}} (如果通过触屏点击则为 true)。</p></form>
ng-model
指令基于它们的状态为 HTML 元素提供了 CSS 类:
input.ng-invalid { background-color: lightblue;}
- ng-empty
- ng-not-empty
- ng-touched
- ng-untouched
- ng-valid
- ng-invalid
- ng-dirty
- ng-pending
- ng-pristine
字面意思相信已经足够理解了,这就用来根据输入框的各种状况来显现相应的样式。
自定义指令
<body ng-app="myApp"><ng-My-Directive1></ng-My-Directive1><div ng-My-Directive2></div><div class="ng-My-Directive3"></div><!-- directive: ng-My-Directive4 --><script>var app = angular.module("myApp", []);app.directive("ngMyDirective1", function() { return { restrict : "E", template : "<h1>用元素来调用的的指令!</h1>" };});app.directive("ngMyDirective2", function() { return { restrict : "A", template : "<h1>用属性来调用的的指令!</h1>" };});app.directive("ngMyDirective3", function() { return { restrict : "C", template : "<h1>用类名来调用的的指令!</h1>" };});app.directive("ngMyDirective4", function() { return { restrict : "M", replace : true,//必须加这行代码,否则注释还是注释 template : "<h1>用注释来调用的的指令!</h1>" };});</script></body>
控制器yu1
原标题:【AngularJS学习笔记】01 指令、服务和过滤器
关键词:JS