点击查看AngularJS系列目录
转载请注明出处:http://www.cnblogs.com/leosx/


Angular的表达式

Angular的表达式和JavaScript代码很像,不过通常Angular的表达式的作用是进行数据绑定。

Angular表达式 PK JavaScript表达式

Angular的表达式和JavaScript的表达式很相像,它们之间有如下不同:

1、Context(上下文): JavaScript 表达式的求值针对全局对象window 的,在Angular中,表达式的求值只是针对于scope对象。

2、Forgiving(容错性):在JavaScript中,尝试访问一个为undefined的属性,你会收到一个异常的。但是在Angular中,会忽略undefinednull

3、没有流程控制语句:在Angular表达式中,你不能使用条件判断、循环语句、或者异常。

4、没有函数声明:您不能在Angular表达式中声明function,哪怕在ng-init 指令中也不行!

5、没有正则表达式:你不能再Angular表达式中使用正则表达式。

6、没有空操作和void方法:你不能再Angular表达式中使用void方法。

7、Filters过滤器:你可以在Angular表达式中使用过滤器去格式化显示。

如果你想运行更复杂的JavaScript代码,你应该在controller里面去声明,在模板中调用。注意,如果我们通常会使用 $eval() 方法去代替eval() 方法。

来一个例子:

文件一:index.html

<span>
1+2={{1+2}}
</span>
文件二:protractor.js
it('should calculate expression in binding', function() {
expect(element(by.binding('1+2')).getText()).toEqual('1+2=3');
});

效果图:

你也可以动态计算不同的表达式:

文件一:index.html

<div ng-controller="ExampleController" class="expressions">
Expression:
<input type='text' ng-model="expr" size="80"/>
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
<li ng-repeat="expr in exprs track by $index">
[ <a href="" ng-click="removeExp($index)">X</a> ]
<code>{{expr}}</code> => <span ng-bind="$parent.$eval(expr)"></span>
</li>
</ul>
</div>

文件二:script.js

angular.module('expressionExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var exprs = $scope.exprs = [];
$scope.expr = '3*10|currency';
$scope.addExp = function(expr) {
exprs.push(expr);
}; $scope.removeExp = function(index) {
exprs.splice(index, 1);
};
}]);

文件三:protractor.js

it('should allow user expression testing', function() {
element(by.css('.expressions button')).click();
var lis = element(by.css('.expressions ul')).all(by.repeater('expr in exprs'));
expect(lis.count()).toBe(1);
expect(lis.get(0).getText()).toEqual('[ X ] 3*10|currency => $30.00');
});

效果图:

上下文(context)

Angular不会使用JavaScript的eval() 方法去计算表达式,而是使用$parse 服务去处理表达式。在Angular中,我们会使用$window 服务和 $location 服务代替JavaScript的全局变量windowlocation变量。

文件一:index.html

<div class="example2" ng-controller="ExampleController">
Name: <input ng-model="name" type="text"/>
<button ng-click="greet()">Greet</button>
<button ng-click="window.alert('Should not see me')">Won't greet</button>
</div>

文件二:script.js

angular.module('expressionExample', [])
.controller('ExampleController', ['$window', '$scope', function($window, $scope) {
$scope.name = 'World'; $scope.greet = function() {
$window.alert('Hello ' + $scope.name);
};
}]);

文件三:protractor.js

it('should calculate expression in binding', function() {
if (browser.params.browser == 'safari') {
// Safari can't handle dialogs.
return;
}
element(by.css('[ng-click="greet()"]')).click(); // We need to give the browser time to display the alert
browser.wait(protractor.ExpectedConditions.alertIsPresent(), 1000); var alertDialog = browser.switchTo().alert(); expect(alertDialog.getText()).toEqual('Hello World'); alertDialog.accept();
});

效果图:

容错性

在Angular中,表达式会忽略undefined 和 null的对象,而不会像JavaScript中一样,会报错!

$event指令

ngClickngFocus 指令,在他们的表达式中,有一个$event 对象。如果引用了jQuery的haunted,该对象是一个jQuery事件对象的实例。

文件一:index.html

<div ng-controller="EventController">
<button ng-click="clickMe($event)">Event</button>
<p><code>$event</code>: <pre> {{$event | json}}</pre></p>
<p><code>clickEvent</code>: <pre>{{clickEvent | json}}</pre></p>
</div>

文件二:script.js

angular.module('eventExampleApp', []).
controller('EventController', ['$scope', function($scope) {
/*
* expose the event object to the scope
*/
$scope.clickMe = function(clickEvent) {
$scope.clickEvent = simpleKeys(clickEvent);
console.log(clickEvent);
}; /*
* return a copy of an object with only non-object keys
* we need this to avoid circular references
*/
function simpleKeys (original) {
return Object.keys(original).reduce(function (obj, key) {
obj[key] = typeof original[key] === 'object' ? '{ ... }' : original[key];
return obj;
}, {});
}
}]);

点击这里,进行查看。

注意上面的例子中,我们使用$event去调用clickMe来实现事件的。但是在 {{$event}}中,却不会显示出任何信息,因为$event 是一个来自于scope之外的binding(绑定)。

一次性绑定

使用:: 开头的表达式被Angular认作是一次性绑定。一次性表达式不会在值发生变化的时候重新计算。第一次绑定完成之后,就再也不会跟着数据变化而变化了。

第一个文件:index.html

<div ng-controller="EventController">
<button ng-click="clickMe($event)">Click Me</button>
<p id="one-time-binding-example">One time binding: {{::name}}</p>
<p id="normal-binding-example">Normal binding: {{name}}</p>
</div>

第二个文件:script.js

angular.module('oneTimeBidingExampleApp', []).
controller('EventController', ['$scope', function($scope) {
var counter = 0;
var names = ['Igor', 'Misko', 'Chirayu', 'Lucas'];
/*
* expose the event object to the scope
*/
$scope.clickMe = function(clickEvent) {
$scope.name = names[counter % names.length];
counter++;
};
}]);

第三个文件:protractor.js

it('should freeze binding after its value has stabilized', function() {
var oneTimeBiding = element(by.id('one-time-binding-example'));
var normalBinding = element(by.id('normal-binding-example')); expect(oneTimeBiding.getText()).toEqual('One time binding:');
expect(normalBinding.getText()).toEqual('Normal binding:');
element(by.buttonText('Click Me')).click(); expect(oneTimeBiding.getText()).toEqual('One time binding: Igor');
expect(normalBinding.getText()).toEqual('Normal binding: Igor');
element(by.buttonText('Click Me')).click(); expect(oneTimeBiding.getText()).toEqual('One time binding: Igor');
expect(normalBinding.getText()).toEqual('Normal binding: Misko'); element(by.buttonText('Click Me')).click();
element(by.buttonText('Click Me')).click(); expect(oneTimeBiding.getText()).toEqual('One time binding: Igor');
expect(normalBinding.getText()).toEqual('Normal binding: Lucas');
});

效果图:

使用一次性绑定的示例:

如果我们只需要我们的表达式执行第一个有效的时候,我们就可以使用我们的一次性表达式。下面,我们有三种用法:

1、在花括号或者属性中使用:

<div name="attr: {{::color}}">text: {{::name | uppercase}}</div>

2、我们在双向绑定中,不希望参数发生变化的时候:

someModule.directive('someDirective', function() {
return {
scope: {
name: '=',
color: '@'
},
template: '{{name}}: {{color}}'
};
});
<div some-directive name="::myName" color="My color is {{::myColor}}"></div>

3、在一个指令中使用:

<ul>
<li ng-repeat="item in ::items | orderBy:'name'">{{item.name}};</li>
</ul>

Angularjs –– Expressions(表达式)的更多相关文章

  1. AngularJS的表达式、指令的学习(2)

    最近没有那么忙,就来系统学习一下AngularJS吧,昨天简单的认识了一下,今天就从表达式入手吧,嘿嘿. 一.AngularJS 表达式 AngularJS表达式写在双大括号内:{{expressio ...

  2. AngularJS:表达式

    ylbtech-AngularJS:表达式 1.返回顶部 1. AngularJS 表达式 AngularJS 使用 表达式 把数据绑定到 HTML. AngularJS 表达式 AngularJS ...

  3. angularjs之表达式

    一:angularjs表达式的解析 angularjs会在运行$digest循环中自动解析表达式,但有时手动解析表达式也是非常用用的. angularjs通过$parse这个内部服务来进行表达式的运算 ...

  4. AngularJs解决表达式闪烁的问题(ng-cloak)

    举例: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...

  5. uva 11234 Expressions 表达式 建树+BFS层次遍历

    题目给出一个后缀表达式,让你求从下往上的层次遍历. 思路:结构体建树,然后用数组进行BFS进行层次遍历,最后把数组倒着输出就行了. uva过了,poj老是超时,郁闷. 代码: #include < ...

  6. Complicated Expressions(表达式转换)

    http://poj.org/problem?id=1400 题意:给出一个表达式可能含有多余的括号,去掉多余的括号,输出它的最简形式. 思路:先将表达式转化成后缀式,因为后缀式不含括号,然后再转化成 ...

  7. (栈的应用5.2.2)POJ 2106 Boolean Expressions(表达式求值)

    /* * POJ_2106.cpp * * Created on: 2013年10月30日 * Author: Administrator */ #include <iostream> # ...

  8. [AngularJS学习笔记] 基础学习01

    2016-06-06开始学习AngularJS AngularJS是会extend HTML的 ng-directives 先学习了四个 ng-app:定义AngularJS Application的 ...

  9. AngularJS基础总结

    w3shools    angularjs教程  wiki   <AngularJS权威教程> Introduction AngularJS is a JavaScript framewo ...

随机推荐

  1. HBRUSH to RGB value

    GetObject函数返回一个LOGBRUSH结构体,包含了COLORREF结构. LOGBRUSH lgbrush; COLORREF color; GetObject((HBRUSH)GetSto ...

  2. Django项目之小博客

    学习了几天Django,学着做了一个简易的小博客,主要用来练习Django基本的操作. 主要用到的命令和Django包.模块等: django.urls.url django.urls.import ...

  3. python基础教程(九)

    python异常 python用异常对象(exception object)来表示异常情况.遇到错误后,会引发异常.如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误 ...

  4. PHP发送邮件功能--ThinkPHP3.2.3

    首先第一步   :在网上down了一个PHPMailer插件,插件地址>https://github.com/PHPMailer/PHPMailer下载解压后,这里我们只需要用到其中两个文件,如 ...

  5. javascript学习笔记-4

    document.getElementByTagName返回的是一个NodeList,这个NodeList和js数组很类似,都可以使用下标读取,如:array[0],但他们也有不同,不同在于不能对No ...

  6. WCF(二)三种通信模式

    WCF在通信过程中有三种模式:请求与答复.单向.双工通信 请求与答复模式 客户端发送请求,然后一直等待服务端的响应答复(异步调用除外),期间处于假死状态,直到服务端有了答复后才能继续执行其他程序 请求 ...

  7. Httprequest 获取url 常用方法

    HttpServletRequest常用获取URL的方法         1.request.getRequestURL() 返回的是完整的url,包括Http协议,端口号,servlet名字和映射路 ...

  8. angular指令笔记(一):ng-options

    1.ng-options指令用途: 在表达式中使用数组或对象来自动生成一个select中的option列表.ng-options与ng-repeat很相似,很多时候可以用ng-repeat来代替ng- ...

  9. JS中的事件&对象

    一.JS中的事件 (一)JS中的事件分类 1.鼠标事件 click/dblclick/onmouseover/onmouseout 2.HTML事件 onload/onscroll/onsubmit/ ...

  10. 搭建自己的CA服务 - OpenSSL CA 实战

    当前网络安全事故不断,如何提升系统安全性是一个系统上线之前必须考虑的重点DFx特性之一.在提升系统安全性的方法中, 给每个端口(通道)加上SSL协议是最通用和有效的一种. 使用SSL就必须要有证书,在 ...