Angular Directive Testing
by Tommy
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.4.8/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script>
<div ng-app="app" ng-controller="ctrl">
Hello {{hello}}
<input type="checkbox" ng-model="showDirective"/>
<div ng-if="showDirective">
<test-callbacks></test-callbacks>
</div>
</div>
JavaScript
var counter = 1;
angular.module('app',[])
.controller('ctrl',[
'$scope',
function($scope){
$scope.hello = 'World!';
}])
.controller('testCtrl', ['testValue','$interval', '$scope', function(testValue, $interval, $scope){
var i = 0;
var w = 0;
var inter = $interval(function(){
console.log('controller:',testValue,'; interval counter:', i++);
}, 1000);
//forever
$interval(function(){
w++;
}, 1000);
$scope.$on('destroy', function(){
console.log('controller destroy fired:', testValue);
});
var watch = $scope.$watch(function(){ return w; }, function(){
console.log('controller watch triggered:', testValue);
});
this.destroy = function(){
console.log('this.destroy controller:', testValue);
$interval.cancel(inter);
watch();
};
}])
.directive('testCallbacks',['$controller',
function($controller){
return {
link: function(scope, elem){
console.log('link fired');
var c = $controller('testCtrl', {testValue: counter++, $scope: scope});
console.log(c);
elem.on('$destroy', function(){
c.destroy();
console.log('destroy fired');
});
},
//compile: function(){
// console.log('compile fired');
//},
controller: function(){
console.log('controller fired');
}
};
}
]);