Angular.js - fiddle

www.angularjs.org

by dandoyon

HTML

<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.min.js"></script>
<div ng:controller="MainController">
    <div class="my-directive1" testVar="10">directive1</div>
    <div class="my-directive2">directive2</div >    
</div>

CSS

div {
    border: 1px solid black;
    float: left;
    padding: 5px;
}

JavaScript

angular.element(document).ready(function() {
    angular.bootstrap(document, ['testModule']);
});

function MainController($scope, $element, $attrs) {
    var self = this;
    $scope.sharedValue = 0;
    
    $scope.setFunction = function(value){  
        console.log("me during set",self);
console.log("setting",value);        
        $scope.sharedValue = value;
        console.log('getting', $scope.sharedValue);
    };
    $scope.getFunction = function(){
         console.log("me during get",self);
        console.log('getting', $scope.sharedValue);
        alert('get done => '+$scope.sharedValue)
    };                                     
}

angular.module('testModule', [])
    .directive('myDirective1', function($compile) {
        return {
            restrict: 'C',
            scope: {testVar:'='},
            controller: 'MainController',
            link: function(scope, element, attrs, ctrs) {                                  
                        //here some stuff which I need compile (removed for demo)
                        element.append(' //compiled ok');
                        //$compile(element.contents())(scope);
    
                        //CONSOLE.LOG => EMPTY CONTROLLER?        
                        console.log(ctrs);
                
                       //SHARED CONTROLLER FUNCTION        
                        element.click(function(){
                            console.log('attrs',attrs);
                            ctrs.setFunction(attrs.testvar);
                        });
                    }
            }
    })
    .directive('myDirective2', function($compile) {
        return {
            restrict: 'C',
            scope: true,
            controller: 'MainController',                
            link: function(scope, element, attrs, ctrs) {       
                        //here some stuff which I need compile (removed for demo)
                        element.append(' //compiled ok');
                       ...