Reputation: 69
I am using angularjs to add dynamic column and its working fine. But the problem is that when I am adding it from function want to set focus to dynamically added element, but if I try after adding function the dom said that element is not yet created. For detail please have look at my code.
$scope.addCol = function(){
//to add column dynamically assign one object to column
$scope.column.push({
spName: "",
spId: 0,
claimedId: 0
});
var id = $scope.column.length - 1;
if($('#sptext'+id).length == 0){
alert("Element was not found");
}else{
alert("Element was found");
$('#sptext'+id).focus();
}
},
Here after adding column the flow goes inside Element was not found.
HTML Code:
<table class="table-striped" id="mainTable" name="mainTable">
<thead style="border-bottom: 1px solid #dddddd;">
<tr ng-if="$index == 0 && counter > 2" ng-repeat="rowContent in rows" id="{{$index}}">
<td name="{{rowContent}}1">
<span >Heading / Question</span>
</td>
<td ng-repeat="colContent in column" id="sp{{$index}}{{$parent.$index}}">
//this span(element) I am trying to set focus while creating dynamically
<span contenteditable id="sptext{{$index}}" >{{colContent.spName}}</span>
<p style="display: none;">{{colContent.spId}}</p>
</td>
</tr>
</thead>
</table>
I am trying to set focus to `<span>` element but its not working.
Please give me any suggestion. Thanks.
Upvotes: 2
Views: 6026
Reputation: 631
As Ganesh mentioned you have to add tabindex to span elements to allow them to be focused. Additionally I advice you to use directive to handle this task. This is more Angular way than finding those elements in jQuery style.
Here you have plnkr with example how to approach this task:
app.controller('MainCtrl', function($scope) {
var item = 'item ';
$scope.list = [item];
var i = 0;
$scope.addToList = function(){
$scope.list.push(item + i);
i++;
}
});
app.directive('focusItem', function() {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.focusItem, function() {
element[0].focus();
});
}
};
});
Hope this helped.
Upvotes: 2
Reputation: 1599
I think, for span to get focus by javascript, span should have tabindex set.
<span contenteditable id="sptext{{$index}}" tabindex="{{$tabindex}}" >{{colContent.spName}}</span>
after this, following should work.
$('#sptext'+id).focus();
Hope it helps.
Upvotes: 1