Angular: Color Fiddle

by Leonardo Trimarchi

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<body ng-controller="myDemoCtrl">

  <h2> Angular socks</h2>
  <p>
    Keep Warm this winter with our 100% wool, 100%cool, AngularJS socks!
  </p>
  <div color-list colors="colorsArray">

  </div>
</body>

CSS

#colorContainer div {
  color: white;
  text-transform: uppercase;
  width: 200px;
  padding: 10px;
  margin: 5px;
  border-radius: 5px;
  -moz-border-radius: 5px;
}

JavaScript

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

angular.module('myApp').controller('myDemoCtrl', function($scope) {
  $scope.colorsArray = ['red', 'green', 'blue', 'purple', 'olive']
});
angular.module('myApp').directive('colorList', function($compile) {
  return {
    restrict: 'AE',
    template: "<button ng-click='showHideColors()' type='button'>" 
    + "{{isHidden ? 'Show Available Colors' : 'Hide Available Colors'}}" 
    + "</button><div ng-hide='isHidden' id='colorContainer'>" 
    + "</div>",
    link: function($scope, $element) {

      $scope.isHidden = true;
      $scope.showHideColors = function() {
        $scope.isHidden = !$scope.isHidden;
      }

      var colorContainer = $element.find('div');
      angular.forEach($scope.colorsArray, function(color) {
        var appendString = "<div style='background-color:" + color + "'>" + color + "</div>";
        colorContainer.append(appendString);
      });
    }
  };
});