Directive terminal
by mslocum
HTML
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular.js"></script>
<div>
<input type="text" ng-model="foo"/>
{{foo}}
<div outside>
{{foo}}
<div inside></div>
</div>
<button ng-click="deleteDiv = true">Delete div</button>
</div>
<br/><br/>
log:<br/>
<textarea id="log"></textarea>
CSS
textarea {
height:20em;
}
JavaScript
var app = angular.module('myApp', []);
function log(str) {
var log = angular.element('#log');
log.val(log.val() + str + '\n');
}
app.controller('ctrl', function($scope) {
console.log($scope);
$scope.foo = "bar";
$scope.deleteDiv = false;
});
app.directive('outside', function(){
return {
transclude: true,
terminal: true,
scope: false,
link: function($scope, $element, $attr, ctrl, $transclude) {
var newScope;
//$scope.foo = "bar";
$scope.$watch('deleteDiv', function(bVal) {
if (bVal) {
newScope.$destroy();
console.log($element);
$element.remove();
}
});
$scope.$watch('foo', function() {
log('outside watch');
});
log('outside ' + $scope.$id + ' : ' + $scope.$$watchers.length);
$transclude(function(clone, _newScope_) {
newScope = _newScope_;
$element.append(clone);
});
log('outside watches ' + $scope.$$watchers.length);
}
}
});
app.directive('inside', function(){
return {
link: function($scope, $element, $attr) {
$scope.$watch('foo', function() {
log('inside watch');
});
log('inside ' + $scope.$id + ' : ' + $scope.$$watchers.length);
}
}
});