angular directive experiment

by Richard Hunter

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.min.js"></script>
<div ng-controller="MainCtrl">
    
    <my-directive>
        <child-directive ng-repeat="color in colors" color="{{color}}"></child-directive>
        <p>
            it's the end of the world as we know it and i feel fine.
            Hello my name is {{ name }}
        </p>
    </my-directive>
</div>
<script type="text/ng-template" id="directive.html">
    <h1>This is my main {{  name }}directive</h1>
    <h2>Current selected is: {{  selected }} </h2>
    <div ng-transclude></div>
</script>

CSS

child-directive {
    width : 100px;
    height : 100px;
    display : inline-block;
}

JavaScript

angular.module('myapp', [])

.controller('MainCtrl', function($scope) {
    $scope.name = 'Richard';
    $scope.colors = ['red', 'green', 'yellow', 'pink'];
})

.directive('childDirective', function () {
    return {
        restrict: 'E',
        require : '^myDirective',
        scope : {
            color : '@'
        },
        
        link : function (scope, element, attrs, controller) {
           
            element.css({ background : scope.color });
            element.on('click', function () {
              
                controller.callIntoParent(scope.color);
            });
        }
    };
})

.directive('myDirective', function () {
    return {
        restrict : 'E',
        scope : {},
        transclude : true,
        controller : function ($scope) {
            
            $scope.selected = 'blue'
            this.callIntoParent = function (name) {
                $scope.$apply(function() {
                    $scope.selected = name;
                });    
            }
        },
        templateUrl : 'directive.html'
        
    };
})

angular.bootstrap(document, ['myapp']);