我有这样的代码
JS
var app = angular.module('app',[]);
app.controller('ctrl',function($scope){
$scope.hello = "hello";
$scope.check = [1,2];
$scope.focus1 = function(){
$scope.setFocusInput0();
};
$scope.focus2 = function(){
$scope.setFocusInput1();
};
});
app.directive('rfocus',function(){
return {
restrict: 'A',
controller: function($scope, $element, $attrs){
var fooName = 'setFocus' + $attrs.rfocus;
$scope[fooName] = function(){alert(1)
$element.focus();
}
},
}
});
HTML
<div ng-app="app" ng-controller="ctrl">
<input ng-repeat="i in check" type="checkbox" rfocus="Input{{$index}}"/>
<button ng-click="focus1()">set focus 1</button>
<button ng-click="focus2()">set focus 2</button>
当我删除ng-repeat并在static中放置复选框时,它正常工作。
答案 0 :(得分:1)
如果使用带有ng-repeat
的指令,您将拥有多个嵌套作用域,因此您应该进行一些更改(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();
}
},
}
});
或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();
}
},
}
});
但他们两个都不会在平常情况下工作。我认为更好solution是改变初始方法。您应该将每个指令传递给它的标识符,即rfocus
并引用变量focus
,它确定当前的焦点元素,这样您就可以在控制器中更改此变量,然后指令将反映它:
<强> 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();
});
},
}
});