Scope and Isolated scope in directive

####Objective####

  1. Example of showing the relationship between scope and isolated scope
  2. Example of using instance attributes in link function in directive and interacting with parent scope

####Notice####

  1. There are 3 scopes in this example.

<!-- more --> <iframe style="margin: 20px 0; width: 100%; height: 300px" src="http://embed.plnkr.co/uQSLHhv6uz2mCdmtPWSg" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

MarkupGithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<div data-my-component attribute-foo="" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" non-iso-attribute="foo">
<h4>Attribute <span class="badge badge-important">@</span></h4>
<div>
<strong>get:</strong>
</div>
<div class="row">
<span class="span3"><strong>set:</strong> <input type="text" ng-model="isolatedAttributeFoo"></span>
<span class="span6 text-success"> <i> This does not update the parent scope.</i> </span>
</div>
<h4>Binding <span class="badge badge-important">=</span></h4>
<div>
<strong>get:</strong>
</div>
<div class="row">
<span class="span3"><strong>set:</strong> <input type="text" ng-model="isolatedBindingFoo"></span>
<span class="span6 text-success"> <i> This does update the parent scope.</i> </span>
</div>
<h4>Expression <span class="badge badge-important">&</span></h4>
<div class="row">
<span class="span3 input-append">
<input type="text" class="input-medium" ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
</span>
<span class="span6 text-success"> <i> And this calls a function on the parent scope.</i> </span>
</div>
<h4>Non Isolated Attribute</h4>
<div class="row">
<span class="span3"> <strong>get:</strong> </span>
<span class="span6 text-success"> <i> This reflects parent scope</i> </span>
</div>
</div>
AngularJSGithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var app = angular.module('ngApp', [])
.directive('myComponent', function () {
"use strict";
return {
scope: {
isolatedAttributeFoo: '@attributeFoo',
isolatedBindingFoo: '=bindingFoo',
isolatedExpressionFoo: '&'
},
link: function (scope, iElement, iAttrs) {
scope.$parent.$watch(iAttrs.nonIsoAttribute, function (newVal, oldVal, scope) {
scope.nonIsoAttribute = newVal;
}, false);
}
};
});
app.controller('MainCtrl', ['$scope', function ($scope) {
'use strict';
$scope.foo = 'Hello!';
$scope.updateFoo = function (newFoo) {
$scope.foo = newFoo;
};
}]);