<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
<meta charset="utf-8">
<title>NG Directive 範例</title>
<style>
.cont-block
{
font-family: Segoe UI; font-size: 10pt;
border: 1px solid gray; padding: 5px; width: 130px;
border-radius: 4px; box-shadow: 5px 5px 10px #444;
}
.memb-list .cont-block { float: left; margin-right: 15px; }
dt { font-weight: bold; color: purple; }
dd { color: brown; }
dd input { width: 80px; }
br { clear: both; }
dd.black { color: black; }
input.red { color: red; }
</style>
</head>
<body ng-controller="defaultCtrl as model">
<h3>Leader</h3>
<div class='memb-list'>
<span class='cont-block'>
<role-card name="model.leader.name" phone-no="model.leader.phone"
name-css="black" phone-css="red" on-change="model.log(newValue)" />
</span>
</div>
<br />
<h3>Members</h3>
<div class='memb-list'>
<span class='cont-block' ng-repeat="member in model.members">
<role-card name="member.name" phone-no="member.phone" />
</span>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script>
<script>
function Contact(name, phone) {
this.name = name;
this.phone = phone;
}
function myViewModel($scope) {
var self = this;
self.leader = new Contact("美國隊長", "0800092000");
self.members = [];
self.members.push(new Contact("鋼鐵人", "28825252"));
self.members.push(new Contact("索爾", "23939889"));
self.members.push(new Contact("浩克", "0800956956"));
self.log = function(msg) {
console.log(msg);
}
}
angular.module("sampleApp", [])
.controller("defaultCtrl", myViewModel)
.directive("roleCard", function() {
return {
restrict: "AE",
scope: {
name: "=",
phone: "=phoneNo",
nameCss: "@",
onChange: "&"
},
link: function(scope, element, attrs) {
scope.phoneCss = attrs.phoneCss;
scope.$watch("phone", function(v) {
if (angular.isFunction(scope.onChange)) {
scope.onChange({newValue: v});
}
});
},
template:
"<dl>" +
"<dt>Name</dt><dd class=\"{{nameCss}}\">{{ name }}</dd>" +
"<dt>Phone</dt><dd>" +
"<input type=\"text\" ng-model=\"phone\" class=\"{{phoneCss}}\"/>" +
"</dd>" +
"</dl>"
}
});
</script>
</body>
</html>