在有多个app的时候,在同一个webpage会重复地用directive呈现每个app。这时,我们需要为html
添加新的element <app-info
,并用这个element来呈现每个app。
在js
目录下,新建directives
文件夹,在该文件夹下,新建文件appinfo.js
和appinfo.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)中的expression
和filter
。
在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的本身部分。