2014-09-06 257 views
2

我正在使用angularjs添加动态列和其工作正常。但问题是,当我从功能添加它想要设置焦点动态添加元素,但如果我尝试后添加功能的DOM说元素还没有创建。详情请看我的代码。Angularjs设置焦点

$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(); 
    } 

}, 

这里加入列后流程进入元素没有被发现。

HTML代码:

<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>&nbsp; 
      </td> 
     </tr> 
    </thead>  
</table>  

I am trying to set focus to `<span>` element but its not working. 

请给我任何建议。谢谢。

+0

也许这将有助于:http://stackoverflow.com/questions/21350572/auto-focus-in-ng-repeat-in-angularjs/21351131#21351131 – 2014-09-06 09:27:24

+0

感谢您的评论它的工作输入参数,但不是为span标签 – user3406754 2014-09-06 09:51:07

回答

2

作为Ganesh提到你必须添加tabindex跨度元素,使他们能够专注。 此外,我建议您使用指令来处理此任务。这比在jQuery风格中找到这些元素更加有角度。

这里有plnkr与例如如何处理这个任务:

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(); 
     }); 
    } 
    }; 
}); 

希望这有助于。

1

我认为,为了得到焦点的跨度,跨度应该有tabindex设置。

<span contenteditable id="sptext{{$index}}" tabindex="{{$tabindex}}" >{{colContent.spName}}</span> 

之后,下面应该工作。

$('#sptext'+id).focus(); 

希望它有帮助。

+0

感谢您的回复。 – user3406754 2014-09-08 05:13:01