Angular focus timing Demonstration

Unhide a div, followed by set focus on an element that just became visible. Details for suggested solution blogged here: http://goo.gl/4rdZa

HTML

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script>
<div class="box">
    <div ng-app="myApp" ng-controller="MyCtrl">
        <button class="btn btn-mini" x-ng-click="onClickReset()"><i class="icon-refresh"></i> reset all</button>
        <br/>
        <h4>Demo 1: Show div, then set focus [Fails]</h4>
        <div class="demobox">
          <div x-ng-show="isShowDemo1">
            <input type="text" x-ng-model="form.color1" x-ng-focus="isFocusDemo1" ng-focus-lost="loseFocus()">
          </div>
        </div>
        <button class="btn" x-ng-click="onClickDemo1()">Show div, then set focus</button>
    </div>
</div>

CSS

@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');
.box {
    margin-top: 10px;
    margin-left: 10px;
}
.demobox {
    width: 400px;
    min-height: 40px;
    padding: 10px;
    border: 2px solid #ccc;
    margin-bottom: 5px;
}
.icon-refresh {
    opacity: 0.65;
}

JavaScript

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

myApp.controller('MyCtrl', function ($scope) {

    $scope.form = {
        color1: '',
        color2: '',
        color3: '',
    };
    $scope.isShowDemo1 = false;
    $scope.isFocusDemo1 = false;
    
    $scope.onClickDemo1 = function() {
        $scope.isShowDemo1 = true;
        $scope.isFocusDemo1 = true;
    };
    
    $scope.loseFocus = function() {
        console.log("setting var");
        $scope.isFocusDemo1 = false;
    };
    
    $scope.onClickReset = function() {
        $scope.isShowDemo1 = false;
        $scope.isFocusDemo1 = false;
    };
    
});

angular.module('ng').directive('ngFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.ngFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);
            
            element.bind('blur', function () {
                if ( angular.isDefined( attrs.ngFocusLost ) ) {
                    scope.$apply( attrs.ngFocusLost );
                    
                }
            });
        }
    };
});