在AngularJS中,“Angular的方法”是什么?
更具体的要求:
当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。
我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。
在AngularJS中,“Angular的方法”是什么?
更具体的要求:
当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。
我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。
当前回答
这工作得很好,并以一种角度的方式来聚焦输入控件
angular.element('#elementId').focus()
虽然这不是一种纯粹的角方式来完成任务,但语法遵循了角风格。Jquery使用Angular间接和直接访问DOM (jQLite => Jquery Light)。
如果需要,这段代码可以很容易地放在一个简单的角指令中,其中element可以直接访问。
其他回答
不是复活僵尸或插入我自己的指令(好吧,这正是我在做的):
https://github.com/hiebj/ng-focus-if
http://plnkr.co/edit/MJS3zRk079Mu72o5A9l6?p=preview
<input focus-if />
(function() {
'use strict';
angular
.module('focus-if', [])
.directive('focusIf', focusIf);
function focusIf($timeout) {
function link($scope, $element, $attrs) {
var dom = $element[0];
if ($attrs.focusIf) {
$scope.$watch($attrs.focusIf, focus);
} else {
focus(true);
}
function focus(condition) {
if (condition) {
$timeout(function() {
dom.focus();
}, $scope.$eval($attrs.focusDelay) || 0);
}
}
}
return {
restrict: 'A',
link: link
};
}
})();
不需要创建自己的指令,可以简单地使用javascript函数来完成一个焦点。
这里有一个例子。
在html文件中:
<input type="text" id="myInputId" />
在javascript文件中,例如在控制器中,你想要激活焦点的地方:
document.getElementById("myInputId").focus();
你可以使用下面的指令,在HTML输入中获取一个bool值来关注它…
//js file
angular.module("appName").directive("ngFocus", function () {
return function (scope, elem, attrs, ctrl) {
if (attrs.ngFocus === "true") {
$(elem).focus();
}
if (!ctrl) {
return;
}
elem.on("focus", function () {
elem.addClass("has-focus");
scope.$apply(function () {
ctrl.hasFocus = true;
});
});
};
});
<!-- html file -->
<input type="text" ng-focus="boolValue" />
你甚至可以在控制器中设置一个函数为ngFocus指令值 注意下面的代码…
<!-- html file -->
<input type="text" ng-focus="myFunc()" />
//controller file
$scope.myFunc=function(){
if(condition){
return true;
}else{
return false;
}
}
这个指令发生在HTML页面渲染时。
不确定依赖超时是否是一个好主意,但这适用于ng-repeat,因为这段代码在angularjs更新DOM后运行,所以你要确保所有对象都在那里:
myApp.directive('onLastRepeat', [function () {
return function (scope, element, attrs) {
if (scope.$last) setTimeout(function () {
scope.$emit('onRepeatLast', element, attrs);
}, 1);
};
}]);
//controller for grid
myApp.controller('SimpleController', ['$scope', '$timeout', '$http', function ($scope, $timeout, $http)
{
var newItemRemoved = false;
var requiredAlert = false;
//this event fires up when angular updates the dom for the last item
//it's observed, so here, we stop the progress bar
$scope.$on('onRepeatLast', function (scope, element, attrs) {
//$scope.complete();
console.log('done done!');
$("#txtFirstName").focus();
});
}]);
HTML有一个属性autofocus。
<input type="text" name="fname" autofocus>
http://www.w3schools.com/tags/att_input_autofocus.asp