Angular+JQ+Bootstrap

by andytjoslin

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<div ng-controller="MyCtrl">
    <br />
    <square var="mySquare"></square>
    <div circle var="myCircle"></div>
    <br />
    <select ng-options="color for color in colors" ng-model="currentColor"></select>
    <br />
    <button ng-click="mySquare.color(currentColor)">Set Square {{currentColor}}</button>
    <button ng-click="myCircle.color(currentColor)">Set Circle {{currentColor}}</button>
</div>

CSS

.square {
    height: 100px;
    width: 100px;
    border: 2px solid black;
}
.circle {
    height: 100px;
    width: 100px;
    border-radius: 50%;
    border: 2px solid black;
}

JavaScript

var app=angular.module('myApp', []);

//Square does not create a new scope, so we assign to its own scope
app.directive('square', function() { 
    return {
        restrict: 'E',
        link: function(scope, elm, attrs) {
            var divElm = elm.find('div');
            scope[attrs.var] = {
                color: function(color) {
                    divElm.css('background',color);
                }
            };
        },
        template: '<div class="square"></div>'
    }
}); 
//Circle does create a new scope, so we assign to its parent scope (the actual controller is the parent)
app.directive('circle', function() {
    return {
        restrict: 'A', //attribute restrict
        scope: {}, //new scope
        link: function(scope, elm, attrs) {
            var divElm = elm.find('div');
            scope.$parent[attrs.var] = {
                color: function(color) {
                    divElm.css('background',color);
                }
            };
        },
        template: '<div class="circle"></div>'
    };
});
        

function MyCtrl($scope) {
    $scope.currentColor = 'red';
    $scope.colors = ['red','green','blue','yellow','purple'];
}