Javascript 用于设置输入焦点的指令无效
基于此问题: 我在这里的示例中使用了名为Javascript 用于设置输入焦点的指令无效,javascript,angularjs,input,angularjs-directive,Javascript,Angularjs,Input,Angularjs Directive,基于此问题: 我在这里的示例中使用了名为focusSearch的相同指令focuseMe: 但是,输入不会在显示时自动获得焦点 步骤1:单击显示搜索按钮 步骤2:输入应自动聚焦 显示搜索 刚刚意识到他最近更新了他的原始问题,更新了他的指令。现在可以这样做了: 这是因为当指令名为focusSearch时,您正在解析focusMe的值。将$parse参数更改为attrs.focusSearch,您的指令就会生效 var model = $parse(attrs.focusSearch); a
focusSearch
的相同指令focuseMe
:
但是,输入不会在显示时自动获得焦点
- 步骤1:单击
按钮显示搜索
- 步骤2:输入应自动聚焦
刚刚意识到他最近更新了他的原始问题,更新了他的指令。现在可以这样做了:
这是因为当指令名为focusSearch时,您正在解析focusMe的值。将$parse参数更改为attrs.focusSearch,您的指令就会生效
var model = $parse(attrs.focusSearch);
angular.module('app', [])
.directive('focusSearch', ['$timeout', '$parse', function($timeout, $parse) {
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
console.log('value=',value);
if (value === true) {
$timeout(function() {
element[0].focus();
});
}
});
// to address @blesh's comment, set attribute value to 'false'
// on blur event:
element.bind('blur', function() {
console.log('blur');
scope.$apply(model.assign(scope, false));
});
}
}
}])
.controller('sidebar',
['$scope',
'$rootScope',
'$timeout',
function($scope,
$rootScope,
$timeout) {
var vs = $scope;
$scope.clickedSearch = function() {
vs.showingSearchInput = true;
}
$scope.hideSearch = function() {
vs.showingSearchInput = false;
}
}]);
app.directive('focusMe', function($timeout) {
return {
scope: { trigger: '=focusMe' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if(value === true) {
//console.log('trigger',value);
//$timeout(function() {
element[0].focus();
scope.trigger = false;
//});
}
});
}
};
});
var model = $parse(attrs.focusSearch);