AngularJS Isolated Scope Experiment
This is a fiddle designed to illustrate isolated scope using the updated and simpler syntax. This is a take on John Lindquist's fiddle which looked like this: http://jsfiddle.net/simpulton/RUbSv/
by Matthew Day
HTML
<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div class="wrap" ng-controller="MyCtrl">
<h2>Controller Scope ("Parent")</h2>
<p>The controller can update the directive as well as be updated by it.</p>
<input ng-model="bar">
<!-- attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated.
-->
<hr>
<h2>Directive Scope ("Child")</h2>
<my-component attribute-foo="{{bar}}" binding-foo="bar"
isolated-expression-foo="updateFoo(newFoo)" >
<div class="inner-wrap">
<h3>Attribute ("@")</h3>
<p>This does not update the controller.</p>
<table>
<thead>
<tr><th>Get</th><th>Set</th></tr>
</thead>
<tbody>
<tr>
<td>{{isolatedAttributeFoo}}</td>
<td><input ng-model="isolatedAttributeFoo"></td>
</tr>
</tbody>
</table>
<h3>Binding ("=")</h3>
<p>This does update the controller.</p>
<table>
<thead>
<tr><th>Get</th><th>Set</th></tr>
</thead>
<tbody>
<tr>
<td>{{isolatedBindingFoo}}</td>
<td><input ng-model="isolatedBindingFoo"></td>
</tr>
</tbody>
</table>
<h3>Expression ("=")</h3>
<p>This calls a function on the controller.</p>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
</div>
</div>
</my-component>
</div>
CSS
* {
font-family: Arial, sans-serif;
}
.wrap {
padding: 30px 20px;
}
h2,
h3 {
color: gray;
text-transform: uppercase;
}
h3 {
color: #333;
font-size: 12px;
margin-top: 20px;
}
p {
font-size: 10px;
margin-bottom: 10px;
}
input {
background: #2c2b2b;
border: none;
color: white;
font-size: 12px;
letter-spacing: 1px;
padding: 6px 12px;
width: 50%;
}
hr {
margin: 30px 0;
}
.inner-wrap {
margin-left: 14px;
}
table {
width: 100%;
}
td,
th {
border: 1px solid rgba(0,0,0,0.3);
padding: 4px 8px;
text-align: center;
}
th {
font-size: 12px;
text-transform: uppercase;
width: 50%;
}
button {
background: thistle;
border: none;
font-size 14px;
padding: 8px;
}
JavaScript
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'@attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.bar = 'Hello!';
$scope.updateFoo = function (newFoo) {
$scope.bar = newFoo;
}
}]);