<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="TestController as vm">
<button type="button" data-ng-click="vm.getItems()">Get Items</button>
<table>
<tr data-ng-repeat="item in vm.items track by item.name">
<td>
<label>Item-{{item.name}}
<input type="checkbox" data-ng-model="item.selected" data-ng-change="vm.itemChanged(item)" />
<my-Directive id="dynamicField{{$index}}" pb-do-focus="item.selected" ng-if="item.selected"></my-Directive>
</label>
</td>
</tr>
</table>
{{vm.items}}
</div>
</body>
</html>
(function() {
angular.module('app', [])
.directive('myDirective', function() {
return {
restict: 'E',
template: '<input type="text"/>',
replace: true
};
})
.directive('pbDoFocus', function() {
return {
restrict: 'A',
link: function(scope, jqelement, attributes) {
scope.$watch(
attributes.pbDoFocus,
function(newValue) {
if (newValue) {
//This example seems to work without a 0ms $timeout, but
//other examples on the web use one. It may be necessary at
//some point to add one.
jqelement[0].focus();
}
});
}
};
});
function TestController($timeout) {
var _this = this;
this.itemChanged = function(item) {
if (!item.selected) return;
$timeout(function() {
//simulate the fact that we went and got a new filtered collection via
//an api call.
//Note that filter does not mutate the original array, it creates a new
//one.
_this.items = _this.items.filter(function(element) {
return element.selected;
});
}, 150); //Reasonable time for REST api call.
//The focused field will remain focused because the DOM element is not
//recreated.
};
this.getItems = function() {
_this.items = [{
name: 'a',
selected: false
}, {
name: 'b',
selected: false
}, {
name: 'c',
selected: false
}];
};
}
TestController.$inject = ['$timeout'];
angular.module('app').controller("TestController", TestController);
})();
/* Styles go here */
This examples shows that an input can be focused within an ngRepeat and will
maintain its focus even if the collection being iterated over changes.