Reputation: 163
I am generating some input fields dynamically using ng-repeat, which is working fine, but I need to focus on the first input generated by this ng-repeat, the inputs are placed based on their sequenceId values. How to achieve this , I tried writing a directive based on this question, [Focus on input generated by ng-repeat, which didn't help.
This is my html file.
<body ng-app ng-controller="MyCtrl">
<div ng-repeat="parameters in inputs | orderBy : 'sequenceId'">
<div ng-if="parameters.parameterType == 'Text'">
<input type="text" class="form-control" placeholder="{{parameters.parameterDesc}}" focused-on="$first"/>
<br/>
</div>
</div>
This is its controller.
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
var inputArr = '[{"parameterName":"PRIORITY","parameterDesc":"Priority","sequenceId":9,"parameterType":"Text","parameterId":"UpdateCase_PRIORITY"},{"parameterName":"REASON","parameterDesc":"Reason","sequenceId":8,"parameterType":"Text","parameterId":"UpdateCase_REASON"},{"parameterName":"TYPE","parameterDesc":"Type","sequenceId":7,"parameterType":"Text","parameterId":"UpdateCase_TYPE"},{"parameterName":"ORIGIN","parameterDesc":"Origin","sequenceId":6,"parameterType":"Text","parameterId":"UpdateCase_ORIGIN"},{"parameterName":"STATUS","parameterDesc":"Status","sequenceId":5,"parameterType":"Text","parameterId":"UpdateCase_STATUS"},{"parameterName":"SUBJECT","parameterDesc":"Subject","sequenceId":4,"parameterType":"Text","parameterId":"UpdateCase_SUBJECT"}]';
$scope.inputs = JSON.parse(inputArr);
});
app.directive('focusedOn', ['$timeout', function($timeout) {
return function($scope, $element, $attrs) {
function focus() {
$timeout(function() {
$element.focus();
}, 20);
}
if (_($attrs.focusedOn).isEmpty()) {
return focus();
}
$scope.$watch($attrs.focusedOn, function(newVal) {
if (newVal) {
focus();
}
});
};
}]);
Upvotes: 1
Views: 972
Reputation: 13953
use the following directive
angular.module('myApp', [])
.directive('focusedOn', function() {
return {
scope: {
focusedOn: '='
},
link: function($scope, $element) {
$scope.$watch('focusedOn', function(shouldFocus) {
if (shouldFocus) {
$element[0].focus();
}
});
}
};
});
And your HTML will be
<input type="text" class="form-control" placeholder="{{parameters.parameterDesc}}" focused-on="$index == 0"/>
Thanks to this stakoveflow answer
Upvotes: 4