对于一个大型的单页应用程序来说,angularjs的controller只应该处理业务逻辑,对于数据则可以交给service、factory来处理,dom相关的操作则交给directive。

directive的一般语法如下:

angular.module('app').directive('singleDirective',function(){

  return {

    restrict:'EA',

    template:'<div></div>',

    //templateUrl:'../index.html',

    controller:function($scope){},

    link:function(scope,element,attrs){...}

  }

});

html结构:

  <div single-directive></div>//在这个场景下,自定义的指令作为 属性(A:attribute) 使用

  <single-directive></single-directive>//在这个场景下,自定义指令作为一个标签元素(E:element)使用

简单介绍一下自定义指令时的设置项:

  restrict-设置为:

    E->元素,<single-directive></single-directive>

    A->属性,<div single-directive></div>

    C->样式类,<div class="single-directive"></div>

    M->注释,<!-- directive: single-directive -->

  restrict的值可以是这些的组合,例如一开始的例子中的“EA”,当然,这个组合随你定义

  scope:

    true -  将为这个directive创建一个新的scope。注意,如果同一个元素中有多个directive需要新的scope的话,它还是只会创建一个scope。

    {} - 将创建一个新的独立的scope。这个独立的scope与一般的scope的区别在于他不是通过原型继承于父scope的。这个独立的scope会创建一个拥有一组来源于父scope的本地scope属性的object hash。本地的定义是对其来源的一组本地scope property的hash映射:

      @或@attr - 传递的是string类型。如:<single-directive attr-name="enen{{name}"></single-directive>。在指令的的scope里就可以写成:{attrName:'@'}或者{attr:'@attrName'},单向绑定

      =或=expression - 设置的是model之间的双向绑定。<single-directive change-name="name"></single-directive>。在指令的的scope里就可以写成:{changeName:'='}或者{anotherName:'=changeName'}

      &或&fn - 设置的是方法的绑定。<single-directive filter-name="filterName()"></single-directive>。在指令的的scope里就可以写成:{filterName:'&'}或者{filter:'&filterName'}

  replace:

    true - 则模板将会替换当前元素,而不是作为子元素添加到当前元素中的。