Angular directives – Scopes
by riddla
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://cdn.rawgit.com/kvz/phpjs/master/functions/strings/nl2br.js"></script>
<div ng-app="editor" class="container">
<div ng-controller="Controller">
<input type="text" ng-model="myControllerValue"> <pre ng-bind="myControllerValue"></pre>
<div class="row">
<my-directive parent-value="true" title="Isolated" ctrl-value="myControllerValue"></my-directive>
<my-directive2 parent-value="true" title="New/Inherited"></my-directive2>
<my-directive3 parent-value="true" title="Scope = false (e.g. shared)"></my-directive3>
</div>
</div>
</div>
JavaScript
var module = angular.module('editor', []);
function Controller($scope, $http) {
$scope.myControllerValue = 'bar';
}
var link = function(scope, iElement, iAttrs, controller, transcludeFn) {
scope.title = scope.title || iAttrs.title;
scope.parentValueAsAttr = iAttrs.parentValue;
debugger;
if (! scope.ctrlValue) {
//scope.ctrlValue = scope.myControllerValue;
}
scope.ctrlValueAsAttr = iAttrs.ctrlValue;
}
function myDirective() {
return {
restrict: 'E',
scope: {
ctrValue: '='
},
template: tpl,
link: link
};
}
function myDirective2() {
return {
restrict: 'E',
scope: true,
template: tpl,
link: link
};
}
function myDirective3() {
return {
restrict: 'E',
scope: false,
template: tpl,
link: link
};
}
module.directive('myDirective', myDirective);
module.directive('myDirective2', myDirective2);
module.directive('myDirective3', myDirective3);
var tpl = '<div class="col-xs-4"><h4 ng-bind="title"></h4><ul class="list-unstyled"><li>ctrValue = <code ng-bind="ctrValue"></code></li><li>myControllerValue as attr = <code ng-bind="myControllerValueAsAttr"></code></li><li>parentValue = <code ng-bind="parentValue"></code><li>parentValue as attr = <code ng-bind="parentValueAsAttr"></code></li><li><input type="text" ng-model="ctrlValue"></li></ul></div>';