带你走近AngularJS系列:

  1. 带你走近AngularJS - 基本功能介绍

  2. 带你走近AngularJS - 体验指令实例

  3. 带你走近AngularJS - 创建自定义指令

------------------------------------------------------------------------------------------------



为什么使用AngularJS 指令?

使用过 AngularJS 的朋友应该最感兴趣的是它的指令。现今市场上的前端框架也只有AngularJS 拥有自定义指令的功能,并且AngularJS 是目前唯一提供Web应用可复用能力的框架。

目前有很多JavaScript 产品提供插件给Web开发人员。例如, Bootstrap 就是当前比较流行的提供样式和JavaScript插件的前端开发工具包。但是开发人员在使用Booostrap中的插件时, 必须切换到JavaScript 模式来写 jQuery 代码来激活插件虽然 jQuery 代码写起来十分简单,但是必须和HTML进行同步,这是一个单调乏味且容易出错的过程。

AngularJS主页展示了一个简单的例子,用于实现Bootstrap中的 Tab功能,可以在页面中轻松添加 Tab 功能,并且使用方法和 ul 标签一样简单。HTML代码如下:


  

BootStrap Tab Component

              
This is the content of the first tab.
                
This is the content of the second tab.
       


JavaScript代码如下:

angular.module('components', []).
  directive('tabs', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {},
      controller: [ "$scope", function($scope) {
        var panes = $scope.panes = [];
                                                                                                                                                                                                                                                                    
        $scope.select = function(pane) {
          angular.forEach(panes, function(pane) {
            pane.selected = false;
          });
          pane.selected = true;
        }
                                                                                                                                                                                                                                                                    
        this.addPane = function(pane) {
          if (panes.length == 0) $scope.select(pane);
          panes.push(pane);
        }
      }],
      template:
        '' +
          '' +
            ''+
              '`pane`.`title`' +
            '' +
          '' +
          '
' +         '