Don't Munge the DOM!
Examples of directives for DOM interaction
by Jeremy Likness
HTML
<script src="https://code.angularjs.org/1.3.4/angular.js"></script>
<div ng-app="myApp" ng-controller="ctrl as ctrl" bind-size="">
<h1>H: {{ctrl.getHeight()}} W: {{ctrl.getWidth()}}</h1>
<input type="text" give-focus="ctrl.one" />
<input type="checkbox" ng-model="ctrl.one" />
<br/>
<input type="text" give-focus="ctrl.two" />
<input type="checkbox" ng-model="ctrl.two" />
<br/>
<input type="text" give-focus="ctrl.three" />
<input type="checkbox" ng-model="ctrl.three" />
</div>
JavaScript
(function (app) {
function SizeService() {
this.width = 0;
this.height = 0;
}
app.directive('giveFocus', ['$timeout', function ($timeout) {
return {
restrict: 'A',
replace: false,
scope: {
binding: '=giveFocus'
},
link: function (scope, element) {
scope.$watch('binding', function () {
var giveFocus = !! scope.binding;
if (giveFocus) {
$timeout(function () {
element[0].focus();
}, 0);
}
});
}
};
}]);
app.service('sizeService', SizeService);
app.directive('bindSize', ['sizeService',
'$window',
'$timeout',
function (ss, w, to) {
return {
restrict: 'A',
replace: false,
link: function (scope, element) {
function bindSize() {
scope.$apply(function () {
ss.width = element[0].clientWidth;
ss.height = element[0].clientHeight;
});
}
w.onresize = bindSize;
to(bindSize, 0);
}
};
}]);
function Controller(sizeService) {
this.one = this.three = false;
this.two = true;
this.getWidth = function () {
return sizeService.width;
};
this.getHeight = function () {
return sizeService.height;
};
}
app.controller('ctrl', Controller);
})(angular.module('myApp', []));