AngularJS的应用(2)

在有多个app的时候,在同一个webpage会重复地用directive呈现每个app。这时,我们需要为html添加新的element <app-info,并用这个element来呈现每个app。

js目录下,新建directives文件夹,在该文件夹下,新建文件appinfo.jsappinfo.html。在appinfo.js中,代码如下:

app.directive('appInfo', function() {
    return {
        restrict: 'E',
        scope: {info: '='},
        templateUrl: 'js/directives/appInfo.html'
    };
});

上述代码用app.directive创建了一个名为appInfo的新的directive。它返回了一个具有三个选项的object:
-restrict 特定该directive将如何在webpage中使用。‘E’说明该directive将被作为新的HTML element使用。
-scope 特定我们通过info特性传递信息到该directive。=告诉directive在<app-info>中寻找名字为info的属性。比如:

<app-info info="shutterbugg"></app-info>

-templeUrl 特定HTML按照顺序呈现scope.info中的数据。appinfo.html如下:

<img class="icon" ng-src="{{info.icon}}">
<h2 class="title">{{info.title}}</h2>
<p class="developer">{{info.developer}}</p>
<p class="price">{{info.price | currency}}</p>

appinfo.html中,我们定义了呈现app具体信息的HTML,用到了(1)中的expressionfilter

在index.html中,我们需要添加相应的javascript<script src="js/directives/appInfo.js"></script>;用这个新的directive作为HTML element <app-info>。比如:

<div class="card">
           <app-info info="move"></app-info>
        </div>

Webpage效果如下:
效果图

为什么要建立自己的directive

-可读性。 Directive可以让你写出更具表达性的HTML。仅仅通过读HTML,你就可以理解app的behavior。
-**可重复利用。**Directive使你创建独立的功能单元。我们可以很容易地把directive插入到另外一个AngularJS app,避免写重复代码。

用户交互之按钮篇

我们新建installApp.js和installApp.html文件。在installApp.js中,我们定义新的directive: installApp

app.directive("installApp", function() {
    return {
        restrict: 'E',
        scope: {},
        templateUrl: 'js/directives/installApp.html',
        link: function(scope, element, attrs) {
            scope.buttonText= "Install",
            scope.installed = false,

            scope.download = function() {
                element.toggleClass('btn-active');
                if(scope.installed) {
                    scope.buttonText = "Install";
                    scope.installed = false;
                } else {
                    scope.buttonText = "Uninstall";
                    scope.installed = true;
                }
            }
        }
    };
});

link选项指向一个函数,当用户点击按钮时,显示Install或者Uninstall。在installApp.html中,我们定义button:

<button class="btn btn-active" ng-click="download()">{{buttonText}}</button>

其中,ng-click指向download()函数。在index.html中,必须要添加installApp.js到<script>中,其它修改如下:

<div class="main" ng-controller="MainController">
      <div class="container">
         <div class="card" ng-repeat="app in apps">
          <app-info info="app"></app-info>
          <install-app></install-info>
        </div>
      </div>
    </div>

总结:
Directive是创建独立的交互式的组件的非常有用的工具。不同于jQuery在HTML上添加新的layer来进行交互,AngularJS将交互视为HTML的本身部分。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值