我正在寻找一种 AngularJS 友好的方式来显示输入框并选择输入中的文本。我尝试使用 Controller 添加逻辑,这是我到目前为止所拥有的:
HTML ComparisonCenterProfiles.html
<div id="saved-profiles" class="select-list" ng-cloak>
<ul>
<li ng-repeat="profile in profiles" ng-class="{'ellipsis': true, 'active': isActive(profile.CompSetId)}">
<span class="save-disk" ng-click="saveActiveProfile()" ng-show="isActive(profile.CompSetId) && profile.IsDirty" style="cursor: pointer;"></span>
<a href="javascript:;" ng-show="!forceRenameProfile || !isActive(profile.CompSetId)" ng-click="setActiveProfile(profile)">{{profile.CompSetName}}</a>
<input type="text" ng-model="profile.CompSetName" ng-show="forceRenameProfile && isActive(profile.CompSetId)" ng-blur="saveActiveProfile()" />
</li>
</ul>
</div>
Javascript
angular
.module('app')
.directive('compProfiles', ['pageMethod', function (pageMethod) {
return {
restrict: 'E',
require: '^compEditor',
controller: ['$scope', function ($scope) {
$scope.saveActiveProfile = function () {
if ($scope.activeProfile.CompSetName.length < 3) {
showAlert('Error',
'<strong>' + $scope.activeProfile.CompSetName + '</strong> is not a valid profile name. Your profile name must have at least 3 characters.',
[
{
text: 'OK',
click: function () {
$scope.forceRenameProfile = true;
hideAlert($(this));
}
}
]);
}
else {
continueSavingProfile();
$scope.forceRenameProfile = false;
}
}
}],
templateUrl: 'Templates/ComparisonCenterProfiles.html'
};
}]);
所以此时,我可以显示输入框,但无法实际选择输入框中的文本,以强调用户需要更改框中的内容。
旁注:我是 AngularJS 的新手,并且来自 jQuery 背景,我当然尝试在元素上使用 focus() 和 select() 但无济于事。
任何想法将不胜感激!
最佳答案
您可以从链接指令中获取输入元素。将此函数添加到指令中:
link: function(scope, element) {
var inputElement = element.find('input');
scope.selectText = function() {
inputElement.setSelectionRange(0, inputElement.value.length)
}
}
在你的 Controller 中你可以调用 selectText 函数:
scope.selectText();
关于angularjs - 通过 Controller 显示输入元素后选择文本框中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600354/