您的位置:首页 > Web前端 > AngularJS

AngularJS之内置指令汇总

2017-06-07 19:33 495 查看
所有以ng前缀开头作为命名空间的指令都是AngularJS提供的内置指令,因此自己开发的指令不要以ng开头。

A、基础ng属性指令

 A.1 布尔属性

 A.1.1 ng-diabled

使用ng-disabled可以把disabled属性绑定到以下表输入字段上:<input>(text/checkbox/radio/ur/email/submit/number)、<textarea>、<select>、<button>。可以通过其属性值可给元素的disabled属性赋值,当表达式为true时是不可用的,当为flase时是可用的。如:

<input type="text" ng-model="someProperty" placeholder="Type to Enable">
<button ng-model="button" ng-disabled="!someProperty">A Button</button>
只有在输入框中输入字段时,按钮才可用。

A.1.2 ng-readonly

通过ng-readonly可以将某个返回值真或假的表达式同是否出现readonly属性进行绑定。如:

<input type="text" ng-model="someProperty"><br/>
<input type="text" ng-readonly="someProperty" value="Some text here"/>

A.1.3  ng-checked

A.1.4 ng-selected

A.2 类布尔属性:ng-href、ng-src虽然不是标准的HTML布尔属性,但是由于行为相似,所以在AngularJS源码内部是和布尔属性同等对待。他们能有效帮助重构和避免错误,因此在改进代码时强烈建议使用它们来代替href和src属性。

A.2.1 ng-href

当使用当前作用域的属性动态创建URL时,应该使用ng-href来代替href。这里潜在的问题是当用户点击一个由插值动态生成的链接时,如果插值尚未生效,将会跳到错误界面(通常是404),这里如果使用ng-href,AngularJS会等到插值生效后再执行点击链接的行为。

<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</head>
<body>
<!-- Always use ng-href when href includes an {{ expression }} -->
<a ng-href="{{myHref}}">I'm feeling lucky, when I load</a>
<!-- href may not load before user clicks -->
<a href="{{myHref}}">I'm feeling 404</a>
<script>
angular.module('myApp', [])
.run(function($rootScope, $timeout) {

$timeout(function()
4000
{
$rootScope.myHref = 'http://google.com';
}, 2000);
})
</script>

</body>
</html>
A.2.2 ng-src

AngularJS会告诉浏览器在ng-src对应的表达式生效之前不要加载图像。

<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</head>
<body>
<h1>Wrong Way</h1>
<img src="{{imgSrc}}" />
<h1>Right way</h1>
<img ng-src="{{imgSrc}}" />
<script>
angular.module('myApp', [])
.run(function($rootScope, $timeout) {

$timeout(function() {
$rootScope.imgSrc = 'https://www.google.com/images/srpr/logo11w.png';
}, 2000);
})
</script>
</body>
</html>


B、在指令中使用子作用域:ng-app和ng-controller是特殊的指令,因为他们会修改嵌套在它们内部的指令的作用域。ng-app为AngularJS应用创建$rootScope或另外一个ng-controller的作用域为原型创建新的的子作用域。

B.1 ng-app

任何具有ng-app属性的DOM元素将被标记为$rootScope的起始点。$rootScope是作用域的起始点,任何嵌套在ng-app内的指令都会继承它。

B.2 ng-controller

内置指令ng-controller的作用域是为嵌套在其中的指令创建一个子作用域,避免将所有的操作和模型都定义在$rootScopeh 。用这个指令可以在一个DOM元素上放置控制器。

值复制:由于原型继承的关系,修改父级对象中的someModel会同时修改子对象中的值。但反之则不行。

<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</head>
<body>
  <div ng-controller="SomeController">
    {{ someModel }}
    <button ng-click="someAction()">Communicate</button>
    <div ng-controller="SomeController">
      {{ someModel }}
      <button ng-click="childAction()">Communicate</button>
    </div>
  </div>
  <script>
    angular.module('myApp', [])
    .controller('SomeController', function($scope) {
      // create a model
      $scope.someModel = 'hello computer';   
      $scope.someAction = function() {
        $scope.someModel = 'hello human, from parent';
      };
    })
    .controller('ChildController', function($scope){
      $scope.childAction = function(){
        $scope.someModel = 'hello human, from child';
      }
    });
  </script>
</body>
</html>


引用复制:如果将某个模型对象设置为字符串,它会通过引用进行共享,因此地子$scope中修改属性也会修改父$scope中的这个属性。无论点击哪个按钮,值都会同步更改。

<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</head>
<body>
<div ng-controller="SomeController">
{{ someModel.someProperty }}
<button ng-click="someAction()">Communicate</button>
<div ng-controller="SomeController">
{{ someModel.someProperty }}
<button ng-click="childAction()">Communicate</button>
</div>
</div>
<script>
angular.module('myApp', [])
.controller('SomeController', function($scope) {
// create a model
$scope.someModel = {
// with a property
someProperty: 'hello computer'
}
// set methods on the $scope itself
$scope.someAction = function() {
$scope.someModel.someProperty = 'hello human, from parent';
};
})
.controller('ChildController', function($scope){
$scope.childAction = function(){
$scope.someModel.someProperty = 'hello human, from child';
}
});
</script>
</body>
</html>B.3 ng-include

使用ng-include时AngularJS会自动创建一个子作用域。如果你想使用某个特定的作用域,例如如myController的作用域,必须在同一个DOM元素上添加ng-controller = "myController"指令,这样当模板加载完毕之后,不会像往常一样从外部作用域继承并创建一个新的子作用域。如:

<div ng-include="/myTemplate.html" ng-controller="myController" ng-init="name = 'World'">Hello {{name}}</div>

 B.4 ng-switch

这个指令和ng-switch-when及on="propertyName"一起使用,可以在propertyName发生变化的时候渲染不同指令到视图中,在switch被调用前我们用ng-switch-default来输出默认值。
<input type="text" ng-model="winner">
<div ng-switch on="winner">
<p ng-switch-default>The Winner Is</p>
<h1 ng-switch-when="Ari">{{winner}}</h1>
</div>
 当输入的是Ari时,文本域下面的div会显示出来。

B.5 ng-view

ng-view指令用来设置将被路由管理和放置在HTML中的视图位置。

B.6 ng-if

使用ng-if指令可以完全根据表达式的值在DOM中生成或移除一个元素。如果赋值给ng-if的表达式的值是false,那对应的元素会从DOM中移除,否则对应元素的一个克隆将被重新插入DOM中。它同ng-show和ng-hide指令最本质的区别是,它不是通过CSS显示或隐藏DOM节点,而是真正生成或移除节点。

ng-if重新创建元素时用的是它们编译后的状态。如果ng-if内部的代码加载之后被JQuery修改过,那么当ng-if的表达式为false这个DOM会被移除,表达式再次为true时这个元素及其内部的子元素及其内部的子元素会被重新插入DOM,此时这些元素的状态一般是它们的原始状态,而不是它们上次被移除时的状态。也就是无论用jQuery的.addCass添加了什么类都都不会存在了。
<div ng-if="2 + 2 === 5">
Won't see this DOM node, not even in the source code
</div>
<div ng-if="2 + 2 === 4">
Hi, I do exist
</div>
B.7 ng-repeat

ng-repeat用来遍历一个集合或为集合中的每个元素生成一个模板实例。集合中的每个元素都会被赋予自己的模板和作用域。同时每个模板实例的作用域中都会暴露一些特殊的属性($index,$first,$middle,$last,$even,$odd)
<body>
<ul ng-controller="PeopleController">
<li ng-repeat="person in people" ng-class="{even: !$even, odd: !$odd}">
{{person.name}} lives in {{person.city}}
</li>
</ul>
<script>
angular.module('myApp', [])
.controller('PeopleController', function($scope) {
$scope.people = [
{name: "Ari", city: "San Francisco"},
{name: "Erik", city: "Seattle"}
];
});
</script>
</body>
B.8 ng-init

ng-init指令用来在指令被调用时设置内部作用域的初始作用域。
<!doctype html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="http://cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</head>
<body>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}
</div>
<script>
angular.module('myApp', []);
</script>
</body>
</html>
 B.9 {{}}

{{}}语法是AngularJS内置的模板语法,它会在内部$scope和视图之间创建绑定。基于这个绑定,只要$scope发生改变,视图就会随之自动更新。事实上它也是指令,是ng-bind的简略形式,用这种形式不需要创建新的元素,因此它常被用在行内文本中。在屏幕可视的区域内使用{{}}会导致页面加载时未渲染的元素发生闪烁,用ng-bind可以避免这个问题。
<body ng-init="greeting='Hello World'">
{{greeting}}
</body>
 B.10 ng-bind

可以用ng-bind将内容与元素绑定在一起避免FOUC(未渲染内容闪烁)。内容会被当作子节点渲染到含有ng-bind指令的元素内。
<body ng-init="greeting='Hello World'">
<p ng-bind="greeting"></p>
</body>
 B.11 ng-cloak

也可以用ng-bind将内容与元素绑定在一起避免FOUC(未渲染内容闪烁),ng-cloak指令会将内部元素隐藏,直到路由调用对应的页面时才显示出来。

B.12 ng-model

用来将input、select、textarea或处自定义表单控件同包含它们的作用域中的属性进行绑定。
<input type="text" ng-model="winner">
B.13 ng-bind-template

同ng-bind指令类似,ng-bind-template用来在视图中绑定多个表达式。
<div ng-bind-template="{{message}}{{name}}"></div>
B.14 ng-show/ng-hide

根据所给表达式的值来显示或隐藏HTML元素。
<div ng-show="2 + 2 == 5">2 + 2 isn't 5, don't show</div>
<div ng-show="2 + 2 == 4">2 + 2 is 4, do show</div>
<div ng-hide="2 + 2 == 5">2 + 2 isn't 5, don't hide</div>
<div ng-hide="2 + 2 == 4">2 + 2 isn't 5, do hide</div>
B.15 ng-change

这个指令会在表单输入发生变化时计算给定表达式的值。因为要处理表单输入,这个指令要和ng-model联合起来一起使用。
<div ng-controller="EquationController">
<input type="text" ng-model="equation.x" ng-change="change()" />
<code>{{ equation.output }}</code>
</div>

<script>
angular.module('myApp', [])
.controller('EquationController', function($scope) {
$scope.equation = {};
$scope.change = function() {
$scope.equation.output = Number($scope.equation.x) + 2;
};
});
</script>
B.16 ng-form

用来在一个表单内部嵌套另一个表单。普通的HTML<form>标签不允许嵌套,但是ng-form可以。这意味着内部所有的子表单都合法时,外部的表单才会合法。这对于用ng-repeat动态创建表单是非常有用的。

下面的CSS类会根据表单的验证状态自动设置:

表单合法时设置ng-valid;

表单不合法时设置ng-invalid;

表单未进行修改时设置ng-priston;

表单进行修改时设置ng-dirty。

Angular不会将表单提交到服务器,除非它指定了action属性。要提交表单时调用哪个JavaScript方法,使用下面两个指令当中的一个。

Ng-submit:在表单元素上使用。

Ng-click:在第一个按钮或submit类型的输入字段上使用。

为了避免处理程序被多次调用,只使用两个指令中的一个。
<style>
input.ng-invalid {
border: 1px solid red;
}
input.ng-valid {
border: 1px solid green;
}
</style>
</head>
<body>
<form name="signup_form"ng-controller="FormController" ng-submit="submitForm()"novalidate>
<div ng-repeat="field in fields"ng-form="signup_form_input">
<input type="text"
name="dynamic_input"
ng-required="field.isRequired"
ng-model="field.name"
placeholder="{{field.placeholder}}" />
<div ng-show="signup_form_input.dynamic_input.$dirty &&signup_form_input.dynamic_input.$invalid">
<span class="error"ng-show="signup_form_input.dynamic_input.$error.required">Thefield is required.</span>
</div>
</div>
<button type="submit"ng-disabled="signup_form.$invalid">Submit All</button>
</form>
<script>
angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.fields = [
{placeholder: 'Username', isRequired: true},
{placeholder: 'Password', isRequired: true},
{placeholder: 'Email (optional)', isRequired: false}
];
$scope.submitForm = function() {
alert("it works!");
};
});
</script>
B.17 ng-click

ng-click用来指定一个元素被点击时调用时调用的方法或表达式。
<divng-controller="CounterController">
<button ng-click="count = count + 1"ng-init="count=0">
Increment
</button>
count: {{count}}
<button ng-click="decrement()">
Decrement
</button>
<div>
<script>
angular.module('myApp', [])
.controller('CounterController', function($scope) {
$scope.decrement = function() {
$scope.count = $scope.count - 1;
};
})
</script>
B.18 ng-select

ng-select用来将数据同HTML的<select>元素进行绑定。这个指令可以和ng-model以及ng-options指令一同使用。Ng-options的值可以是一个内涵表达式,简单来说就是它可以接受一个数组或对象,并对它们进行循环,将内部的内容提供给select标签内部的选项。它的数据源可以是数组和对象。
<div ng-controller="CityController">
<select ng-model="city" ng-options="city.name for cityin cities">
<option value="">Choose City</option>
</select>
Best City: {{ city.name }}
</div>
<script>
angular.module('myApp', [])
.controller('CityController', function($scope) {
$scope.cities = [
{name: 'Seattle'},
{name: 'San Francisco'},
{name: 'Chicago'},
{name: 'New York'},
{name: 'Boston'}
];
});
</script>
B.19 ng-submit

ng-submit用来将表达式同onsubmit事件进行绑定。这个指令会阻止默认行为,除非表单不含有action属性。
<form ng-submit="submit()" ng-controller="FormController">
Enter text and hit enter:
<input type="text" ng-model="person.name"name="person.name" />
<input type="submit" name="person.name"value="Submit" />
<code>people={{people}}</code>
<ul>
<li  ng-repeat="(index,object) in people">{{ object.name }}</li>
</ul>
</form>
<script>
angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.person = {
name: null
};
$scope.people = [];
$scope.submit = function() {
if ($scope.person.name) {
$scope.people.push({name: $scope.person.name});
$scope.person.name = '';
}
};
});
</script>
B.20 ng-class

使用ng-class动态设置元素的类,方法是绑定一个代表所有需要添加的类的表达式。重复的类不会添加。当表达式发生改变时,先前添加的类会被移除,新类会被添加。
<style>
.red {
background-color: red;
}
</style>
</head>
<body>
<divng-controller="LotteryController">
<div ng-class="{red: x > 5}">
You won!
</div>
<button ng-click="x = generateNumber()" ng-init="x =0">Draw Number</button>
<p>Number is: {{ x }}</p>
&l
92ef
t;/div>
<script>
angular.module('myApp', [])
.controller('LotteryController', function($scope) {
$scope.generateNumber = function() {
return Math.floor((Math.random()*10)+1);
}
})
</script>
B.21 ng-attr-(suffix)

当AngularJS编译DOM时会查找花括号{{}}内的表达式。这些表达式会被自动注册到$watch服务中并更新到$digest循环中,成为它的一部分。

有时候浏览器会对属性进行苛刻的限制。SVG就是一个例子:
<svg>
<circlecx=”{{cx}}”></circle>
</svg>
 运行上面的代码会抛出一个错误,指出有一个非法属性。可以用ng-attr-cx来解决这个问题。即:
<svg>
<circleng-attr-cx=”{{cx}}”></circle>
</svg>


参考书籍:《AngularJS权威教程》——【美】Ari Lerner著
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: