JSFiddle - React, Tailwind, and code Playground
by warren guo
HTML
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<script src="https://code.angularjs.org/1.2.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<h3>普通的 Angular</h3>
{{customerName}}: <input ng-model="credit" />
<button ng-click="saveChanges(' [普通的Angular] ')">保存</button>
<h3>自定义指令</h3>
<my-dir
name="{{customerName}}"
amount="credit"
save="saveChanges(' [自定义指令] ')">
</my-dir>
</body>
JavaScript
// 主模块
var myApp = angular.module("myApp", []);
// 添加 controller
myApp.controller("myCtrl", function($scope) {
$scope.customerName = "葡萄城控件";
$scope.credit = 8800;
$scope.saveChanges = function(source) {
alert("保存了来自" + source + "的变更");
};
});
// 添加 directive
myApp.directive("myDir", function() {
return {
restrict: "E",
scope: {
name: "@", // name 值传递 (字符串,单向绑定)
amount: "=", // amount 引用传递(双向绑定)
save: "&" // 保存操作
},
template:
"<div>" +
" {{name}}: <input ng-model='amount' />" +
" <button ng-click='save()'>保存</button>" +
"</div>",
replace: true,
transclude: false,
link: function (scope, element, attrs) {
console.log("initial value for name:" + scope.name);
console.log("initial value for amount:" + scope.amount);
element.css("background", "yellow");
scope.$watch("amount", function (newVal, oldVal) {
console.log("amount has changed " + oldVal + " >> " + newVal);
});
scope.$watch("name", function (newVal, oldVal) {
console.log("name has changed " + oldVal + " >> " + newVal);
});
}
}
});