Angular - Isolated Scope
Simple directive with isolated scope and variables of all three types
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<body ng-app="myApp" ng-controller="myCtrl">
<h3>Plain Angular</h3>
{{customerName}}: <input ng-model="credit" />
<button ng-click="saveChanges('plain html')">Save</button>
<div
>
{{credit}}
</div>
<h3>Custom Directive</h3>
<my-dir
name="{{customerName}}"
amount="credit"
save="saveChanges('custom directive')">
</my-dir>
</body>
JavaScript
// the main (app) module
var myApp = angular.module("myApp", []);
// add a controller
myApp.controller("myCtrl", function($scope) {
$scope.customerName = "Eddie";
$scope.credit = 123;
$scope.saveChanges = function(source) {
alert("changes saved from " + source);
};
});
// add a directive
myApp.directive("myDir", function() {
return {
restrict: "E",
scope: {
name: "@", // by value
amount: "=", // by reference
save: "&" // event
},
template:
"<div>" +
" {{name}}: <input ng-model='amount' />" +
" <button ng-click='save()'>Save</button>" +
"</div>",
replace: true,
transclude: false,
link: function (scope, element, attrs) {
// show initial values: by-val members will be undefined
console.log("initial value for name:" + scope.name);
console.log("initial value for amount:" + scope.amount);
// change element just to show we can
element.css("background", "yellow");
// log changes to the 'amount' variable
scope.$watch("amount", function (newVal, oldVal) {
console.log("amount has changed " + oldVal + " >> " + newVal);
});
// log changes to the 'name' variable
scope.$watch("name", function (newVal, oldVal) {
console.log("name has changed " + oldVal + " >> " + newVal);
});
}
}
});