首页 > Web开发 > 详细

Angularjs –– Expressions(表达式)

时间:2015-10-23 18:29:33      阅读:208      评论:0      收藏:0      [点我收藏+]

点击查看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;
    }, {});
  }
}]);

点击这里,进行查看。

Angularjs –– Expressions(表达式)

原文:http://www.cnblogs.com/leosx/p/4905113.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!