AngularJS Element Directive

by martijngr

HTML

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.3/angular.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<div ng:app="MyApp">
    <script type="text/ng-template" id="good.html">
        <div>
            <form>
                <select ng-model="customer.color" ng-options="c.Name for c in colors"></select>
            </form>
            <button ng-click="closeForm()">Cancel</button>
        </div>
    </script>
    
    <div ng-controller="appCtrl">
        <button ng-click="ShowEditCustomerForm()">Edit customer</button>
        
        <div ng-show="showCustomerEdit">
        <customer-Edit
            visible="showCustomerEdit"
            customer="customer"
        ></customer-Edit>
        </div>
    </div>
</div>

CSS

.number {
    width:50px;
    height:20px;
    margin:5px;
    float:left;
    color:white;
}
.red{
    background:red;
}
.blue{
    background:blue;
}
.green{
    background:green;
}

JavaScript

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

myMod.directive('customerEdit', function () {
    return {
        restrict:'E',
        replace: true,
        templateUrl: 'good.html',
        scope: {
            visible: '=',
            originalCustomer: '=customer'
        },
        controller: function($scope, $element, $attrs){
            
            $scope.$watch('visible', function(newValue){
                if(newValue == true){
                    
                    var colors = [];
                    colors.push({Id: 1, Name: 'green'});
                    colors.push({Id: 2, Name: 'blue'});
                    colors.push({Id: 3, Name: 'red'});
                    colors.push({Id: 4, Name: 'yellow'});
                    
                    $scope.colors = colors;
                    
                    if($scope.originalCustomer){
                        $scope.customer = {};
                        angular.copy($scope.originalCustomer, $scope.customer);
                        $scope.customer.color = _.findWhere($scope.colors, {Id: $scope.customer.color.Id});
                    }
                }
            });
            
            $scope.closeForm = function(){
                $scope.visible=false;
            }
            
        }
    };
})


function appCtrl($scope) {
    $scope.showCustomerEdit = false;
    $scope.customer = {};
    $scope.customer.color = {Id: 2};
    
    $scope.ShowEditCustomerForm = function(){
        $scope.showCustomerEdit = true;
    }
}