At case of using directive with ng-repeat, you will have several nested scopes, so you should make some changes(plunker):
app.directive('rfocus',function(){
return {
scope:{
rfocus:'@'
},
restrict: 'A',
controller: function($scope, $element, $attrs){
var fooName = 'setFocus' + $scope.rfocus;
$scope.$parent.$parent[fooName] = function(){
alert(1)
$element.focus();
}
},
}
});
Or this variant:
<input ng-repeat="i in check" type="checkbox" rfocus="'Input' + $index"/>
Javascript:
app.directive('rfocus',function(){
return {
restrict: 'A',
controller: function($scope, $element, $attrs){
var fooName = 'setFocus' + $scope.$eval($attrs.rfocus);
$scope.$parent.$parent[fooName] = function(){
alert(1)
$element.focus();
}
},
}
});
But both of them will not work at plain situation. I think better solution is to change initial approach. You should pass to each directive it's identifier, i.e. rfocus and reference to variable focus, which determines current focused element, so you can change this variable in your controller and then directives will reflect it:
HTML:
<div ng-app="app" ng-controller="ctrl">
<input ng-repeat="i in check" type="checkbox" rfocus="{{$index}}" focus='{{focus}}'/>
<button ng-click="focusClick(0)">set focus 1</button>
<button ng-click="focusClick(1)">set focus 2</button>
<input type="checkbox" rfocus="2" focus='{{focus}}'/>
<button ng-click="focusClick(2)">set focus 3</button>
</div>
Javascript:
var app = angular.module('app',[]);
app.controller('ctrl',function($scope){
$scope.hello = "hello";
$scope.check = [1,2];
$scope.focus = 0;
$scope.focusClick = function(index){
$scope.focus = index;
};
});
app.directive('rfocus',function(){
return {
scope:{
rfocus:'@',
focus:'@'
},
restrict: 'A',
controller: function($scope, $element, $attrs){
$scope.$watch('focus', function(){
if($scope.rfocus == $scope.focus)
$element.focus();
});
},
}
});
setFocusInput0function andsetFocusInput1function in your main controller?