Checkbox w/ auto focus textbox

####Objective####

  1. Show the different between Controller and Directive
  2. Example of using instance [attributes][0] with watch in link function in directive

<!-- more --> <iframe style="margin:20px 0; width: 100%; height: 300px" src="http://embed.plnkr.co/84NRZHlGeL3LqS4XgTGY" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

MarkupGithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div class='row'>
<span class='span4'>
controller version
</span>
<span class='span8'>
<input type="checkbox" id='checkbox' ng-model="isChecked">
<input type="text" id="name">
</span>
</div>
<div class='row'>
<span class='span4'>
directive version
</span>
<span class='span8'>
<input type="checkbox" ng-model="isChecked2">
<input type="text" xng-focus='isChecked2'>
</span>
</div>

AngularJSGithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var app = angular.module('ngApp', [])
.directive('xngFocus', function () {
"use strict";
return function (scope, element, iattrs) {
scope.$watch(iattrs.xngFocus,
function (newValue) {
newValue && element.focus();
}, true);
};
});
app.controller('MainCtrl', ['$scope', function ($scope) {
'use strict';
$scope.$watch('isChecked', function (newV) {
newV && $('#name').focus();
}, true);
}]);
[0]:http://docs.angularjs.org/api/ng.$compile.directive.Attributes