GVKun编程网logo

AngularJs expression详解及简单示例(angularjs $q)

10

对于AngularJsexpression详解及简单示例感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解angularjs$q,并且为您提供关于AngularJsUsing$location

对于AngularJs expression详解及简单示例感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解angularjs $q,并且为您提供关于AngularJs Using $location详解及示例代码、AngularJS Batarang – 什么是interceptedExpressions?、AngularJs Forms详解及简单示例、AngularJs Modules详解及示例代码的宝贵知识。

本文目录一览:

AngularJs expression详解及简单示例(angularjs $q)

AngularJs expression详解及简单示例(angularjs $q)

表达式(Expressions)是类Javascript的代码片段,通常放置在绑定区域中(如{{expression}})。表达式通过$parse服务(http://code.angularjs.org/1.0.2/docs/api/ng.$parse)解析执行。

  例如,以下是angular中有效的表达式:

  1. 1+2
  2. 3*10 | currency
  3. user.name

一、Angular表达式 vs. Js 表达式

  这很容易让人将angular视图表达式联想为javascript表达式,但这并不完全正确,因为angular不是通过javascript的eval()对表达式进行求值。你可以将angular表达式想象为带有以下差异的javascript表达式:

  1. 属性求值:所有属性的求值是对于scope的,而javascript是对于window对象的。
  2. 宽容(forgiving):表达式求值,对于undefined和null,angular是宽容的,但Javascript会产生NullPointerExceptions(-_-!!!!怎么我没见过)。
  3. 没有流程控制语句:在angular表达式里,我们不能做以下任何的事:条件分支、循环、抛出异常。
  4. 过滤器(filters):我们可以就将表达式的结果传入过滤器链(filter chains)。例如将日期对象转换为本地指定的人类可读的格式。

  另一方面,如果我们想(在angular表达式中)执行任意的Javascript代码,我们可以将那些代码写到Controller的一个方法中并调用它。如果我们想在javascript中eval()一个angular表达式,可以使用$eval()方法。

rush:js;"> <Meta charset="UTF-8"> expression-e1

三、Forgiving(宽容,容错?)

  表达式求值对undefined和null是宽容的。在javascript中,当a不是object的时候,对a.b.c求值,那么将会抛出一个异常。有时候这对于通用语言来说是合理的,而表达式求值主要用于数据绑定,一般形式如下:

  如果a不存在,没有任何显示似乎比抛出异常更加合理(除非我们等待服务端响应,不一会儿就会被定义)。如果表达式求值时不够宽容,那么我们如此混乱地写绑定代码:

  相似地,引用一个函数a.b.c()时,如果它是undefined或者null,那么简单地返回undefined。

四、没有控制流程语句(No Control Flow Statements)

  我们不可以在表达式中写流程控制语句。背后的原因是,angular的核心体系是应用的逻辑应当在controller(的scope)里面,而不是在view里面。如果我们需要在视图表达式中加入条件分支、循环或者抛出异常的话,可以委托javascript方法去代替(可以调用scope中的方法)。

五、过滤器(Filters)

  当我们向用户呈现数据时,我们可能需要将数据从原始格式转换为友好(可读性强)的格式。例如,我们有一个数据对象需要在显示给用户之前根据地域进行格式化。我们可以将表达式传递给一连串的过滤器,如:

  这表达式求值器可简单地传递name的值到uppercase过滤器中。

  链式过滤器使用这种语法:

  我们也可以传送用冒号分割的参数到filter中,例如,以两位小数的格式显示123:

六、前缀”$”

  我们可能会感到奇怪,前缀”$”的意义是什么?它是angular为了使本身的API名称能够区别于其他的API而使用的一个简单的前缀(防止冲突)。如果angular不使用$,那么对a.length()求值将返回undefined。因为a和angular本身都没有定义这个属性。

  考虑到angular将来的版本可能会选择增加length这个方法,这将令这个表达式的行为发生改变。更糟糕的是,我们开发者可能会创建一个length属性,那么将与angular发生冲突。这个问题存在因为angular通过增加方法扩展了当前存在的对象。通过加入前缀”$”,angular保留了特定的namespace,所以angular的开发者与使用angular的开发者都可以和谐共处。

AngularJs  Using $location详解及示例代码

AngularJs Using $location详解及示例代码

一、What does it do?

  $location服务分析浏览器地址栏中的URL(基于window.location),让我们可以在应用中较为方便地使用URL里面的东东。在地址栏中更改URL,会响应到$location服务中,而在$location中修改URL,也会响应到地址栏中。

  $location服务:

暴露当前浏览器地址栏的URL,所以我们可以

1.注意和观察URL
2.改变URL

当用户做以下操作时,与浏览器一起同步URL:

1.改变地址栏
2.单击后退或者前进按钮(或者点击一个历史链接)。
3.单击一个链接

将URL对象描绘为一系列的方法(protocol,host,path,search,hash)。

1. 比较$location和window.location

  1) 目的:window.location和$location服务,都允许对当前浏览器的location进行读写访问。

  2) API:window.location暴露一个未经加工的对象,附带一些可以直接修改的属性;而$location服务则是暴露一些jQuery风格的getter/setter方法。

  3) 与angular应用声明周期的整合:$location知道关于所有内部声明周期的阶段,与$watch等整合;而window.location则不行。

  4) 与HTML5 API无缝结合:是(with a fallback for legacy browsers,对于低版本的浏览器有兼容手段?);而window.location则没有。

  5) 知道应用加载的文档根目录(docroot)或者上下文(context):window.location不行,wnidow.location.path会返回”/docroot/子路径”;而$location.path()返回真实的docroot。

2. When should I use $location?

  在应用中,任何需要对当前URL的改变作出响应,或者想去改变当前浏览器的URL的时候。

3. What does it not do?

  当浏览器URL改变的时候,不会导致页面重新加载(page reload)。如果需要做这件事情(更改地址,实现page reload),请使用较低级别的API,$window.location.href。

二、General overview of the API(API的总体概述)

  $location 服务可以根据它初始化时的配置而有不同的表现。默认配置是适合大多数应用的,其他配置定制,可以开启一些新特性。

  当$location服务初始化完毕,我们可以以jQuery风格的getter、setter方法来使用它,允许我们获得或者改变当前浏览器的URl。

1. $location service configuration

  想配置$location服务,需要获得$locationProvider(http://code.angularjs.org/1.0.2/docs/api/ng.$locationProvider),并设置以下参数:

html5Mode(mode):{boolean},true - see HTML5 mode;false - see Hashbang mode,默认: false。(下面的章节会解释各种mode)

hashPrefix(prefix):{string},hashbang使用的前缀(html5Mode为false时,使用hashbang mode,以适应不支持HTML5 mode的浏览器),默认:''!''

2. Getter and setter methods

  $location 服务为只读的URL部分(absUrl,protocol,host,port)提供getter方法,也提供url,path,search,hash的getter、setter方法。

 // get the current path
  $location.path();

  // change the path
  $location.path(''/newValue'')

  所有setter方法都返回同一个$location对象,以实现链式语法。例如,在一句里面修改多个属性,链式setter方法类似:

  $location.path(‘/newValue'').search({key:value});

  有一个特别的replace方法,可以用作告诉$location服务,在下一次与浏览器同步时,使用某个路径代替最新的历史记录,而不是创建一个新的历史记录。当我们想实现重定向(redirection)而又不想使后退按钮(后退按钮回重新触发重定向)失效时,replace方法就很有用了。想改变当前URL而不创建新的历史记录的话,我们可以这样做:

          $location.path(‘/someNewPath'').replace();

  注意,setter方法不会马上更新window.location。相反,$location服务会知道scope生命周期以及合并多个$location变化为一个,并在scope的$digest阶段一并提交到window.location对象中。正因为$location多个状态的变化会合并为一个变化,到浏览器中,只调用一次replace()方法,让整个commit只有一个replace(),这样不会使浏览器创建额外的历史记录。一旦浏览器更新了,$location服务会通过replace()方法重置标志位,将来的变化将会创建一个新的历史记录,除非replace()被再次调用。

           Setter and character encoding

  我们可以传入特殊字符到$location服务中,服务会按照RFC3986标准,自动对它们进行编码。当我们访问这些方法时:

  1. 所有传入$location的setter方法的值,path()、search()、hash(),都会被编码。
  2. getter方法(没参数)返回的值都是经过解码的,如path(),search(),hash()。
  3. 当我们调用absUrl()方法时,返回的值是包含已编码部分的完整url。
  4. 当我们调用url()方法时,返回的是包含path、search和hash部分的已经编码的url,如/path?search=1&b=c#hash。 

三、Hashbang and HTML5 Modes

$location服务有两个配置模式,可以控制浏览器地址栏的URL格式:Hashbang mode(默认)与基于使用HTML5 History API的HTML5 mode。在两种模式下,应用都使用相同的API,$location服务会与正确的URL片段、浏览器API一起协作,帮助我们进行浏览器URL变更以及历史管理。

 

 

1. Hashbang mode (default mode)

  在这个模式中,$location在所有浏览器中都使用Hashbang URL。查看下面的代码片段,可以了解更多:

it(''should show example'', inject(
  function($locationProvider) {
    $locationProvider.html5mode = false;
    $locationProvider.hashPrefix = ''!'';
  },
  function($location) {
  // open http://host.com/base/index.html#!/a
  $location.absUrl() == ''http://host.com/base/index.html#!/a'';
  $location.path() == ''/a'';
  $location.path(''/foo'');
  $location.absUrl() == ''http://host.com/base/index.html#!/foo'';
  $location.search() == {};//search没东东的时候,返回空对象
  $location.search({a: ''b'', c: true});
  $location.absUrl() == ''http://host.com/base/index.html#!/foo?a=b&c'';
  $location.path(''/new'').search(''x=y'');//可以用字符串的方式更改search,每次设置search,都会覆盖之前的search
  $location.absUrl() == ''http://host.com/base/index.html#!/new?x=y'';
  }
));

  Crawling your app(让google能够对我们的应用进行索引)

  如果我们想让我们的Ajax应用能够被索引,我们需要在head中增加一个特殊的meta标签:

                <meta name="fragment" content="!" />

  这样做,将让爬虫机器人使用_escaped_fragment_参数请求当前的链接,让我们的服务器认识爬虫机器人,并提供对应的HTML快照。想了解更多关于这个技术的信息,可以查看https://developers.google.com/webmasters/ajax-crawling/docs/specification?hl=zh-CN

四、HTML5 mode

  在HTML5模式中,$location服务的getter、setter通过HTML5的History API与浏览器URL进行交互,允许使用正规的path、search模块,代替hashbang的模式。如果部分浏览器不支持HTML5 History API,$location服务会自动退回到使用hashbang URL的模式。为了让我们能够从不清楚显示我们的应用的浏览器是否支持history API的担心中解脱出来,使用$location服务是一个正确的、最佳的选择。

  在旧版浏览器中打开一个正规的URL会转换为hashbangURL。

  在现代浏览器中打开一个hashbangURL,会重写为一个正规的URL。

1. 向前兼容旧版浏览器

  对于支持HTML5 history API的浏览器,$location回使用它们去写path和search。如果浏览器不支持history API,$location会转为提供Hashbang URL。这是$location服务自动转换的。

2. HTML link rewriting

  当我们使用history API mode的时候,我们对于不同的浏览器,需要不同的链接,但我们只需要提供正规的URL即可,例如<a href=”/some?foo=bar”>link</a>

当用户单击这个超链接时:

在旧的浏览器中,URL会改为/index.html#!/some?foo=bar

在现代浏览器中,URL会改为/some?foo=bar

  在下面的情况中,链接不会被重写,而是会使页面加载到对应Url中:

包含target的超链接:<a href="/ext/link?a=b" target="_self">link</a>

到不同domain的绝对链接:<a href="http://angularjs.org/">link</a>

设置了base路径后,通过” /”开头的链接到不同base路径的超链接:<a href="/not-my-base/link">link</a>

3. server side

  使用这个方式,在服务端请求URL重定向,通常,我们需要重定向我们所有的链接到我们的应用中。(例如index.html)。

4. Crawling your app

  与之前相同

5. Relative links

  确保检查所有相对链接、图片、脚本等。我们必须在<head>中指定base url(<base href="/my-base">),并在所有地方使用绝对url(以/开头)。因为相对URL会根据document的初始路径(通常与应用的root有所不同),转化为绝对url。(relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application)。

  我们十分鼓励在document root中运行允许使用History API的angular应用,因为这很好地照顾到相对链接的问题。

6. Sending links among different browsers

  (这里讲解了两种模式的地址可以适应不同浏览器,自动转换,又重复讲一次……)

7. 例子

  在这例子中,可以看到两个$location实例,两个都是html5 mode,但在不同的浏览器上,所以我们可以看到两者之间的不同点。这些$location服务与两个假的“浏览器”连接。每一个input代表浏览器的地址栏。

  注意,当我们输入hashbang地址到第一个“浏览器”(或者第二个?),它不会重写或重定向另外的Url,这个转换过程只会发生在page reload的时候。

<!DOCTYPE html>
<html ng-app>
<head>
  <base href=""/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>fake-browser</title>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
  </style>
</head>
<body>
<div ng-non-bindable>
  <div id="html5-mode" ng-controller="Html5Cntl">
    <h4>Browser with History API</h4>
    <div ng-address-bar browser="html5"></div><br><br>
    $location.protocol() = {{$location.protocol()}}<br>
    $location.host() = {{$location.host()}}<br>
    $location.port() = {{$location.port()}}<br>
    $location.path() = {{$location.path()}}<br>
    $location.search() = {{$location.search()}}<br>
    $location.hash() = {{$location.hash()}}<br>
    <a href="http://www.host.com/base/first?a=b">/base/first?a=b</a> |
    <a href="http://www.host.com/base/sec/ond?flag#hash">sec/ond?flag#hash</a> |
    <a href="/other-base/another?search">external</a>
  </div>
  <div id="hashbang-mode" ng-controller="HashbangCntl">
    <h4>Browser without History API</h4>
    <div ng-address-bar browser="hashbang"></div><br><br>
    $location.protocol() = {{$location.protocol()}}<br>
    $location.host() = {{$location.host()}}<br>
    $location.port() = {{$location.port()}}<br>
    $location.path() = {{$location.path()}}<br>
    $location.search() = {{$location.search()}}<br>
    $location.hash() = {{$location.hash()}}<br>
    <a href="http://www.host.com/base/first?a=b">/base/first?a=b</a> |
    <a href="http://www.host.com/base/sec/ond?flag#hash">sec/ond?flag#hash</a> |
    <a href="/other-base/another?search">external</a>
  </div>
</div>
<script src="../angular.js" type="text/javascript"></script>
<script type="text/javascript">
  function FakeBrowser(initUrl, baseHref) {
    this.onUrlChange = function(fn) {
      this.urlChange = fn;
    };

    this.url = function() {
      return initUrl;
    };

    this.defer = function(fn, delay) {
      setTimeout(function() { fn(); }, delay || 0);
    };

    this.baseHref = function() {
      return baseHref;
    };

    this.notifyWhenOutstandingRequests = angular.noop;
  }
  var browsers = {
    html5: new FakeBrowser(''http://www.host.com/base/path?a=b#h'', ''/base/index.html''),
    hashbang: new FakeBrowser(''http://www.host.com/base/index.html#!/path?a=b#h'', ''/base/index.html'')
  };

  function Html5Cntl($scope, $location) {
    $scope.$location = $location;
  }

  function HashbangCntl($scope, $location) {
    $scope.$location = $location;
  }

  function initEnv(name) {
    var root = angular.element(document.getElementById(name + ''-mode''));
    angular.bootstrap(root, [
      function ($compileProvider, $locationProvider, $provide) {
        debugger;
      $locationProvider.html5Mode(true).hashPrefix(''!'');

      $provide.value(''$browser'', browsers[name]);
      $provide.value(''$document'', root);
      $provide.value(''$sniffer'', {history:name == ''html5''});

      $compileProvider.directive(''ngAddressBar'', function () {
        return function (scope, elm, attrs) {
          var browser = browsers[attrs.browser],
              input = angular.element(''<input type="text">'').val(browser.url()),
              delay;

          input.bind(''keypress keyup keydown'', function () {
            if (!delay) {
              delay = setTimeout(fireUrlChange, 250);
            }
          });

          browser.url = function (url) {
            return input.val(url);
          };

          elm.append(''Address: '').append(input);

          function fireUrlChange() {
            delay = null;
            browser.urlChange(input.val());
          }
        };
      });
    }
    ]);
    root.bind(''click'', function (e) {
      e.stopPropagation();
    });
  }

  initEnv(''html5'');
  initEnv(''hashbang'');
</script>
</body>
</html>


五、附加说明

1. Page reload navigation

  $location服务仅仅允许我们改变URl;它不允许我们重新加载页面(reload the page)。当我们需要改变URL且reload page或者跳转到其他页面时,我们需要使用低级点得API,$window.location.href。

2. Using $location outside of the scope life-cycle

  $location知道angular的scope life-cycle。当浏览器的URL发生改变时,它会更新$location,并且调用$apply,所以所有$watcher和$observer都会得到通知。当我们再$digest阶段中修改$location,不会出现任何问题;$location会将这次修改传播到浏览器中,并且通知所有$watcher、$observer。当我们需要在angular外面改变$location时(例如在DOM事件中或者在测试中),我们必须调用$apply,以传播这个变化。

3. $location.path() and ! or / prefixes

  path可以直接使用”/”开始;$location.path()setter会在value没有以”/”开头时自动补上。

  注意”!”前缀,在Hashbang mode中,不属于$location.path()的一部分。它仅仅是hashPrefix。

六、Testing with the $location service

  在测试中使用$location服务的时候,是处于angular scope life-cycle外面的。这意味着我们需要负责调用scope.apply()。  

describe(''serviceUnderTest'', function() {
  beforeEach(module(function($provide) {
    $provide.factory(''serviceUnderTest'', function($location){
    // whatever it does...
    });
  });
  it(''should...'', inject(function($location, $rootScope, serviceUnderTest) {
    $location.path(''/new/path'');
    $rootScope.$apply();
    // test whatever the service should do...
  }));
});
 

七、Migrating from earlier AngularJS releases

  在早期的angular中,$location使用hashPath或者hashSearch去处理path和search方法。在这个release中,当有需要的时候,$location服务处理path和search方法,然后使用那些获得得信息去构成hashbang URL(例如http://server.com/#!/path?search=a)。

八、Two-way binding to $location

  angular compiler当前不支持方法的双向绑定(https://github.com/angular/angular.js/issues/404)。如果我们希望对$location对象实现双向绑定(在input中使用ngModel directive),我们需要指定一个额外的model属性(例如:locationPath),并加入两个$watch,监听两个方向上的$location更新,例如:

<input type="text" ng-model="locationPath" />

// js - controller
$scope.$watch(''locationPath'', function(path) {
  $location.path(path);
);
$scope.$watch(''$location.path()'', function(path) {
  scope.locationPath = path;
});

以上就是关于AngularJs Using $location的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!

您可能感兴趣的文章:
  • AngularJS通过$location获取及改变当前页面的URL
  • AngularJS内建服务$location及其功能详解
  • AngularJS的$location使用方法详解

AngularJS Batarang – 什么是interceptedExpressions?

AngularJS Batarang – 什么是interceptedExpressions?

我正在使用AngularJS 1.3.0稳定版本和Batarang Chrome扩展。在手表树中,我注意到在我的许多范围内有一些叫做“interceptedExpression”的东西。这是什么或什么场景创建了interceptedExpression?
什么是interceptedExpression?

interceptedExpression是$parse返回的一个函数。
为什么在Batarang被称为被拦截的表达?

因为在角度源代码中声明的函数是一个名为interceptedExpression的命名函数。
>什么场景创建一个interceptedExpression?

我知道的一个场景是当你在一个指令中使用=声明一个本地的scope属性。这将在batarang中创建一个interceptedExpression记录。见角src here。

AngularJs Forms详解及简单示例

AngularJs Forms详解及简单示例

      控件(input、select、textarea)是用户输入数据的一种方式。Form(表单)是这些控件的集合,目的是将相关的控件进行分组。

  表单和控件提供了验证服务,所以用户可以收到无效输入的提示。这提供了更好的用户体验,因为用户可以立即获取到反馈,知道如何修正错误。请记住,虽然客户端验证在提供良好的用户体验中扮演重要的角色,但是它可以很简单地被绕过,因此,客户端验证是不可信的。服务端验证对于一个安全的应用来说仍然是必要的。

一、Simple form

  理解双向数据绑定的关键directive是ngModel。ngModel提供了从model到view和view到model的双向数据绑定。并且,它还向其他directive提供API,增强它们的行为。

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="SimpleForm">
<head>
  <meta charset="UTF-8">
  <title>PropertyEvaluation</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
  </style>
</head>
<body>
<div ng-controller="MyCtrl">
  <form novalidate>
    名字: <input ng-model="user.name" type="text"><br/>
    Email: <input ng-model="user.email" type="email"><br/>
    性别: <input value="男" ng-model="user.gender" type="radio">男
    <input value="女" ng-model="user.gender" type="radio">女
    <br/>
    <button ng-click="reset()">还原上次保存</button>
    <button ng-click="update(user)">保存</button>
  </form>
  <pre>form = {{user | json}}</pre>
  <pre>saved = {{saved | json}}</pre>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("SimpleForm", []);
  app.controller("MyCtrl", function ($scope,$window) {
    $scope.saved = {};

    $scope.update = function(user) {
      $scope.saved = angular.copy(user);
    };

    $scope.reset = function() {
      $scope.user = angular.copy($scope.saved);
    };

    $scope.reset();
    //不合法的值将不会进入user
  });
</script>
</body>
</html>


 

二、Using CSS classes

  为了让form以及控件、ngModel富有样式,可以增加以下class:

  1. ng-valid
  2. ng-invalid
  3. ng-pristine(从未输入过)
  4. ng-dirty(输入过)

  下面的例子,使用CSS去显示每个表单控件的有效性。例子中,user.name和user.email都是必填的,但当它们修改过之后(dirty),背景将呈现红色。这确保用户不会直到与表单交互之后(提交之后?),发现未能满足其有效性,才为一个错误而分心。

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="CSSClasses">
<head>
  <meta charset="UTF-8">
  <title>CSSClasses</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    .css-form input.ng-invalid.ng-dirty {
      background-color: #fa787e;
    }
    .css-form input.ng-valid.ng-dirty {
      background-color: #78fa89;
    }
  </style>
</head>
<body>
<div ng-controller="MyCtrl">
  <form novalidatename="formName">
    名字: <input ng-model="user.name" type="text" required><br/>
    Email: <input ng-model="user.email" type="email" required><br/>
    性别: <input value="男" ng-model="user.gender" type="radio">男
    <input value="女" ng-model="user.gender" type="radio">女
    <br/>
    <button ng-click="reset()">RESET</button>
    <button ng-click="update(user)">SAVE</button>
  </form>
  <pre>form = {{user | json}}</pre>
  <pre>saved = {{saved | json}}</pre>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("CSSClasses", []);
  app.controller("MyCtrl", function ($scope,$window) {
    $scope.saved = {};
    $scope.update = function(user) {
      $scope.saved = angular.copy(user);
    };

    $scope.reset = function() {
      $scope.user = angular.copy($scope.saved);
    };

    $scope.reset();
    //不合法的值将不会进入user
  });
</script>
</body>
</html>

三、Binding to form and control state

  在angular中,表单是FormController的一个实例。表单实例可以随意地使用name属性暴露到scope中(这里没看懂,scope里面没有一个跟form的name属性一直的property,但由于有“document.表单名”这种方式,所以还是可以获取到的)。相似地,控件是NgModelController的实例。控件实例可以相似地使用name属性暴露在form中。这说明form和控件(control)两者的内部属性对于使用标准绑定实体(standard binding primitives)绑定在视图中的这个做法是可行的。

  这允许我们通过以下特性来扩展上面的例子:

  1. RESET按钮仅仅在form发生改变之后才可用。
  2. SAVE按钮仅仅在form发生改变而且输入有效的情况下可用。
  3. 为user.email和user.agree定制错误信息。
<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="ControlState">
<head>
  <meta charset="UTF-8">
  <title>ControlState</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    .css-form input.ng-invalid.ng-dirty {
      background-color: #fa787e;
    }
    .css-form input.ng-valid.ng-dirty {
      background-color: #78fa89;
    }
  </style>
</head>
<body>
<div ng-controller="MyCtrl">
  <form novalidatename="formName">
    名字: <input ng-model="user.name" name="userName" type="text" required><br/>
    <div ng-show="formName.userName.$dirty&&formName.userName.$invalid">
      <span>请填写名字</span>
    </div>
    Email: <input ng-model="user.email" name="userEmail" type="email" required><br/>
    <div ng-show="formName.userEmail.$dirty && formName.userEmail.$invalid">提示:
      <span ng-show="formName.userEmail.$error.required">请填写Email</span>
      <span ng-show="formName.userEmail.$error.email">这不是一个有效的Email</span>
    </div>
    性别: <input value="男" ng-model="user.gender" type="radio">男
    <input value="女" ng-model="user.gender" type="radio">女
    <br/>
    <input type="checkbox" ng-model="user.agree" name="userAgree" required/>我同意:
    <input type="text" ng-show="user.agree" ng-model="user.agreeSign" required/>
    <br/>
    <div ng-show="!formName.userAgree || !user.agreeSign">请同意并签名~</div>
    <button ng-click="reset()" ng-disabled="isUnchanged(user)">RESET</button>
    <button ng-click="update(user)" ng-disabled="formName.$invalid || isUnchanged(user)">SAVE</button>
  </form>
  <pre>form = {{user | json}}</pre>
  <pre>saved = {{saved | json}}</pre>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("ControlState", []);
  app.controller("MyCtrl", function ($scope,$window) {
    $scope.saved = {};
    $scope.update = function(user) {
      $scope.saved = angular.copy(user);
    };

    $scope.reset = function() {
      $scope.user = angular.copy($scope.saved);
    };

    $scope.isUnchanged = function(user) {
      return angular.equals(user, $scope.saved);
    };

    $scope.reset();
    //不合法的值将不会进入user
  });
</script>
</body>
</html>


四、Custom Validation

  angular为大多数公共的HTML表单域(input,text,number,url,email,radio,checkbox)类型提供了实现,也有一些为了表单验证的directive(required,pattern,,inlength,maxlength,min,max)。

  可以通过定义增加定制验证函数到ngModel controller(这里是连在一起的ngModelController吗?)中的directive来定义我们自己的验证插件。为了得到一个controller,directive如下面的例子那样指定了依赖(directive定义对象中的require属性)。

          Model到View更新 - 无论什么时候Model发生改变,所有在ngModelController.$formatters(当model发生改变时触发数据有效性验证和格式化转换)数组中的function将排队执行,所以在这里的每一个function都有机会去格式化model的值,并且通过NgModelController.$setValidity(http://code.angularjs.org/1.0.2/docs/api/ng.directive:ngModel.NgModelController#$setValidity)修改控件的验证状态。

          View到Model更新 - 一个相似的方式,无论任何时候,用户与一个控件发生交互,将会触发NgModelController.$setViewValue。这时候轮到执行NgModelController$parsers(当控件从DOM中取得值之后,将会执行这个数组中所有的方法,对值进行审查过滤或转换,也进行验证)数组中的所有方法。

  在下面的例子中我们将创建两个directive。

       第一个是integer,它负责验证输入到底是不是一个有效的整数。例如1.23是一个非法的值,因为它包含小数部分。注意,我们通过在数组头部插入(unshift)来代替在尾部插入(push),这因为我们想它首先执行并使用这个控件的值(估计这个Array是当作队列来使用的),我们需要在转换发生之前执行验证函数。

        第二个directive是smart-float。他将”1.2”和”1,2”转换为一个合法的浮点数”1.2”。注意,我们在这不可以使用HTML5的input类型”number”,因为浏览器不允许用户输入我们预期的非法字符,如”1,2”(它只认识”1.2”)。

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="CustomValidation">
<head>
  <meta charset="UTF-8">
  <title>CustomValidation</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    .css-form input.ng-invalid.ng-dirty {
      background-color: #fa787e;
    }
    .css-form input.ng-valid.ng-dirty {
      background-color: #78fa89;
    }
  </style>
</head>
<body>
<div>
  <form novalidatename="formName">
    <div>
      大小(整数 0 - 10):<input integer type="number" ng-model="size" name="size" min="0" max="10"/>{{size}}<br/>
      <span ng-show="formName.size.$error.integer">这不是一个有效的整数</span>
      <span ng-show="formName.size.$error.min || formName.size.$error.max">
        数值必须在0到10之间
      </span>
    </div>
    <div>
      长度(浮点数):
      <input type="text" ng-model="length" name="length" smart-float/>
      {{length}}<br/>
      <span ng-show="formName.length.0error.float">这不是一个有效的浮点数</span>
    </div>
  </form>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("CustomValidation", []);
  var INTEGER_REGEXP = /^\-?\d*$/;
  app.directive("integer", function () {
    return {
      require:"ngModel",//NgModelController
      link:function(scope,ele,attrs,ctrl) {
        ctrl.$parsers.unshift(function (viewValue) {//$parsers,View到Model的更新
          if(INTEGER_REGEXP.test(viewValue)) {
            //合格放心肉
            ctrl.$setValidity("integer", true);
            return viewValue;
          }else {
            //私宰肉……
            ctrl.$setValidity("integer", false);
            return undefined;
          }
        });
      }
    };
  });
  var FLOAT_REGEXP = /^\-?\d+(?:[.,]\d+)?$/;
  app.directive("smartFloat", function () {
    return {
      require:"ngModel",
      link:function(scope,ele,attrs,ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
          if(FLOAT_REGEXP.test(viewValue)) {
            ctrl.$setValidity("float", true);
            return parseFloat(viewValue.replace(",", "."));
          }else {
            ctrl.$setValidity("float", false);
            return undefined;
          }
        });
      }
    }
  });
</script>
</body>
</html>

五、Implementing custom form control (using ngModel)

  angular实现了所有HTML的基础控件(input,select,textarea),能胜任大多数场景。然而,如果我们需要更加灵活,我们可以通过编写一个directive来实现自定义表单控件的目的。

  为了制定控件和ngModel一起工作,并且实现双向数据绑定,它需要:

实现render方法,是负责在执行完并通过所有NgModelController.$formatters方法后,呈现数据的方法。

调用$setViewValue方法,无论任何时候用户与控件发生交互,model需要进行响应的更新。这通常在DOM事件监听器里实现。
  可以查看$compileProvider.directive获取更多信息。

  下面的例子展示如何添加双向数据绑定特性到可以编辑的元素中。

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="CustomControl">
<head>
  <meta charset="UTF-8">
  <title>CustomControl</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    div[contenteditable] {
      cursor: pointer;
      background-color: #D0D0D0;
    }
  </style>
</head>
<body ng-controller="MyCtrl">
<div>
  <div contenteditable="true" ng-model="content" title="点击后编辑">My Little Dada</div>
  <pre>model = {{content}}</pre>
  <button ng-click="reset()">reset model tirgger model to view($render)</button>
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("CustomControl", []);
  app.controller("MyCtrl", function ($scope) {
    $scope.reset = function() {
      $scope.content = "My Little Dada";
      //在这里如何获取NgModelController呢?如果你们知道,希望可以指点指点!谢谢
    };
  });
  app.directive("contenteditable", function () {
    return {
      require:"ngModel",
      link:function (scope, ele, attrs, ctrl) {
        //view -> model
        ele.bind("blur keyup",function() {
          scope.$apply(function() {
            console.log("setViewValue");
            ctrl.$setViewValue(ele.text());
          });
        });

        //model -> view
        ctrl.$render = function(value) {
          console.log("render");
          ele.html(value);
        };
        //读取初始值
        ctrl.$setViewValue(ele.text());
      }
    };
  });
</script>
</body>
</html>

您可能感兴趣的文章:
  • AngularJs Managing Service Dependencies详解
  • AngularJs Injecting Services Into Controllers详解
  • AngularJs Creating Services详解及示例代码
  • AngularJs Using $location详解及示例代码
  • AngularJs Understanding Angular Templates
  • AngularJs E2E Testing 详解
  • AngularJs Understanding the Controller Component
  • AngularJs Understanding the Model Component
  • AngularJs Dependency Injection(DI,依赖注入)
  • AngularJs Scope详解及示例代码
  • AngularJs Modules详解及示例代码
  • AngularJs IE Compatibility 兼容老版本IE
  • AngularJs 国际化(I18n/L10n)详解
  • AngularJs directive详解及示例代码
  • AngularJs unit-testing(单元测试)详解

AngularJs Modules详解及示例代码

AngularJs Modules详解及示例代码

一、什么是Module?

  很多应用都有一个用于初始化、加载(wires是这个意思吗?)和启动应用的main方法。angular应用不需要main方法,作为替代,module提供有指定目的的声明式,描述应用如何启动。这样做有几项优点:

  1. 这过程是声明描述的,更加容易读懂。
  2. 在单元测试中,不需要加载所有module,这对写单元测试很有帮助。
  3. 额外的module可以被加载到情景测试中,可以覆盖一些设置,帮助进行应用的端对端测试(end-to-end test)。
  4. 第三方代码可以作为可复用的module打包到angular中。
  5. module可以通过任意顺序或并行加载(取决于模块执行的延迟性,due to delayed nature of module execution)。
  6.  

二、The Basics(基础)

  我们很迫切想知道如何让Hello World module能够工作。下面有几个关键的事情要注意:

module API(http://code.angularjs.org/1.0.2/docs/api/angular.Module)

注意的提及的在<html ng-app=”myApp”>中的myApp module,它让启动器启动我们定义的myApp module。

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <title>basics</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
  </style>
</head>
<body>
<div>
  {{''Kitty'' | greet}}
</div>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var simpleModule = angular.module("myApp", []);
  simpleModule.filter("greet", function () {
    return function(name) {
      return "Hello " + name + " !";
    }
  });
</script>
</body>
</html>

三、(Recommended Setup)推荐设置

  虽然上面的例子很简单,它不属于大规模的应用。我们建议将自己的应用按照如下建议,拆分为多个module:

  1. service module,用于声明service。
  2. directive module,用于声明directive。
  3. filter module,用于声明filter。
  4. 应用级别的module,依赖上述的module,并且包含初始化的代码。

  这样划分的理由是,当我们在测试的时候,往往需要忽略那些让测试变得困难的初始化代码。通过将代码分成独立的module,在测试中就可以很容易地忽略那些代码。这样,我们就可以更加专注在加载相应的module进行测试。

  上面的只是一个建议,可以随意地按照自己的需求制定。

四、Module Loading & Dependencies(模块加载和依赖)

  module是配置(configuration)的集合,执行在启动应用的进程中应用的块(blocks)。在它的最简单的形式中,由两类block组成:

  1.配置块(configuration blocks):在provider注册和配置的过程中执行的。只有provider和constant(常量?)可以被注入(injected)到configuration blocks中。这是为了避免出现在service配置完毕之前service就被执行的意外。

  2.运行块(run blocks):在injector创建完成后执行,用于启动应用。只有实例(instances)和常量(constants)可以被注入到run block中。这是为了避免进一步的系统配置在程序运行的过程中执行。

angular.module(''myModule'', []).

  config(function(injectables) { // provider-injector

  // 这里是config block的一个例子

  // 我们可以根据需要,弄N个这样的东东

  // 我们可以在这里注入Providers (不是实例,not instances)到config block里面

  }).

  run(function(injectables) { // instance-injector

  // 这里是一个run block的例子

  // 我们可以根据需要,弄N个这样的东东

  // 我们只能注入实例(instances )(不是Providers)到run block里面

});

  a) Configuration Blocks(配置块)

  有一个方便的方法在module中,它相当于config block。例如:

angular.module(''myModule'', []).
 value(''a'', 123).
  factory(''a'', function() { return 123; }).
  directive(''directiveName'', ...).
  filter(''filterName'', ...);

// 等同于

angular.module(''myModule'', []).
 config(function($provide, $compileProvider, $filterProvider) {
  $provide.value(''a'', 123)
  $provide.factory(''a'', function() { return 123; })
  $compileProvider.directive(''directiveName'', ...).
  $filterProvider.register(''filterName'', ...);
});

  configuration blocks被应用的顺序,与它们的注册的顺序一致。对于常量定义来说,是一种额外的情况,即放置在configuration blocks开头的常量定义。

  b) Run Blocks(应用块)

  run block是在angular中最接近main方法的东东。run block是必须执行,用于启动应用的代码。它将会在所有service配置、injector创建完毕后执行。run block通常包含那些比较难以进行单元测试的代码,就是因为这个原因,这些代码应该定义在一个独立的module中,让这些代码可以在单元测试中被忽略。 

  c) Dependencies(依赖)

  一个module可以列出它所依赖的其他module。依赖一个module,意味着被请求(required)的module(被依赖的)必须在进行请求(requiring)module(需要依赖其他module的module,请求方)加载之前加载完成。换一种说法,被请求的module的configuration block会在请求的module的configuration block执行前执行(before the configuration blocks or the requiring module,这里的or怎么解释呢?)。对于run block也是这个道理。每一个module只能够被加载一次,即使有多个其他module需要(require)它。 

  d) Asynchronous Loading(异步加载)

  module是管理$injector配置的方法之一,不用对加载脚本到VM做任何事情。现在已经有现成的项目专门用于处理脚本加载,也可以用到angular中。因为module在加载的过程中不做任何事情,它们可以按照任意的顺序被加载到VM中。脚本加载器可以利用这个特性,进行并行加载。 

            五、Unit Testing(单元测试)

  在单元测试的最简单的形式中,其中一个是在测试中实例化一个应用的子集,然后运行它们。重要的是,我们需要意识到对于每一个injector,每一个module只会被加载一次。通常一个应用只会有一个injector。但在测试中,每一个测试用例都有它的injector,这意味着在每一个VM中,module会被多次加载。正确地构建module,将对单元测试有帮助,正如下面的例子:

  在这个例子中,我们准备假设定义如下的module:

angular.module(''greetMod'', []).
factory(''alert'', function($window) {
   return function(text) {
     $window.alert(text);
   };

})
.value(''salutation'', ''Hello'')
.factory(''greet'', function(alert, salutation) {
   return function(name) {
     alert(salutation + '' '' + name + ''!'');
   };
});

  让我们写一些测试用例:

describe(''myApp'', function() {
  // 加载应用响应的module,然后加载指定的将$window重写为mock版本的测试module,
  // 这样做,当进行window.alert()时,测试器就不会因被真正的alert窗口阻挡而停止
  //这里是一个在测试中覆盖配置信息的例子
  beforeEach(module(''greetMod'', function($provide) {//这里看来是要将真正的$window替换为以下的东东
    $provide.value(''$window'', {
      alert: jasmine.createSpy(''alert'')
    });
  }));
   
  // inject()会创建一个injector,并且注入greet和$window到测试中。
  // 测试不需要关心如何写应用,只需要关注如何测试应用。
  it(''should alert on $window'', inject(function(greet, $window) {
    greet(''World'');
    expect($window.alert).toHaveBeenCalledWith(''Hello World!'');
  }));
  
  // 这里是在测试中通过行内module和inject方法来覆盖配置的方法
  it(''should alert using the alert service'', function() {
    var alertSpy = jasmine.createSpy(''alert'');
    module(function($provide) {
      $provide.value(''alert'', alertSpy);
    });
    inject(function(greet) {
      greet(''World'');
      expect(alertSpy).toHaveBeenCalledWith(''Hello World!'');
    });
  });
});
您可能感兴趣的文章:
  • Angular 理解module和injector,即依赖注入
  • 深入浅析AngularJS中的module(模块)
  • 详解AngularJS中module模块的导入导出
  • AngularJS Module方法详解
  • Angular ng-repeat 对象和数组遍历实例
  • 基于AngularJS实现iOS8自带的计算器
  • 微信+angularJS的SPA应用中用router进行页面跳转,jssdk校验失败问题解决
  • AngularJS 实现JavaScript 动画效果详解
  • 深入理解AngularJS中的ng-bind-html指令和$sce服务
  • Angular Module声明和获取重载实例代码

我们今天的关于AngularJs expression详解及简单示例angularjs $q的分享已经告一段落,感谢您的关注,如果您想了解更多关于AngularJs Using $location详解及示例代码、AngularJS Batarang – 什么是interceptedExpressions?、AngularJs Forms详解及简单示例、AngularJs Modules详解及示例代码的相关信息,请在本站查询。

本文标签:

上一篇从零开始学习Node.js系列教程之基于connect和express框架的多页面实现数学运算示例

下一篇表格隔行换色 css expression(表格隔行换色)