ng:directive - shared and isolated scope
by Krzysztof Safjanowski
HTML
<div ng-app="binding">
<div ng-controller="oneWayBinding">
value: {{ value }}
<div one-way-binding value="{{ value }}"></div>
</div>
<div ng-controller="twoWayBinding">
value: {{ value }}
<div two-way-binding value="value"></div>
</div>
</div>
JavaScript
angular.module('binding', [])
.controller('oneWayBinding', function($scope) {
$scope.value = 2;
})
.directive('oneWayBinding', function() {
return {
scope: {
readOnlyValue: '@value'
},
link: function(scope) {
scope.increaseValue = function() {
scope.readOnlyValue++;
};
},
template: 'Read only value: {{ readOnlyValue }} <button ng-click="increaseValue()">Increase</button>'
};
})
.controller('twoWayBinding', function($scope) {
$scope.value = 4;
})
.directive('twoWayBinding', function() {
return {
scope: {
readOnlyValue: '=value'
},
link: function(scope) {
scope.increaseValue = function() {
scope.readOnlyValue++;
}
},
template: 'Read only value: {{ readOnlyValue }} <button ng-click="increaseValue()">Increase</button>',
};
})