我跟着this thread创建了一个宽度灵活的输入字段:JSBin:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="YourApp">
<div ng-controller="YourController">
<div edit-inline>
<input id="flexibleInput" ng-model="title" ></input>
<span id="flexibleDummy" style="visibility:hidden; position:absolute; left:-1000px; top:-1000">blblapx</span>
</div>
</div>
<script type="text/javascript">
angular.module('YourApp', [])
.controller('YourController', ['$scope', function ($scope) {
$scope.title = "very very vry very very very very very very very long"
}])
.directive("editInline", function(){
return function(scope, element, attr){
var elInput = element.find('#flexibleInput');
var elDummy = element.find('#flexibleDummy');
var inputText = elInput.val();
elInput.bind("keydown keyup", function(){
var inputText = elInput.val();
elDummy.html(inputText);
option1 = elDummy[0].offsetWidth;
elInput.css('width', option1 + 'px');
});
}
});
</script>
</body>
</html>
问题是第一次加载页面时,输入框的宽度没有调整;我们需要修改其内容以触发调整。
有谁知道如何解决这个问题?
答案 0 :(得分:1)
您可以使用 $ timeout 在下一个摘要周期中触发更改。(查看代码段的工作情况)
angular.module('YourApp', [])
.controller('YourController', ['$scope', function($scope) {
$scope.title = "very very vry very very very very very very very long"
}])
.directive("editInline", function($timeout) {
return function(scope, element, attr) {
var elInput = element.find('#flexibleInput');
var elDummy = element.find('#flexibleDummy');
var inputText = elInput.val();
elInput.bind("keydown keyup", function() {
scope.modFun();
});
scope.modFun = function() {
var inputText = elInput.val();
elDummy.html(inputText);
option1 = elDummy[0].offsetWidth;
elInput.css('width', option1 + 'px');
}
$timeout(function () {
scope.modFun();
});
}
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="YourApp">
<div ng-controller="YourController">
<div edit-inline>
<input id="flexibleInput" ng-model="title" />
<span id="flexibleDummy" style="visibility:hidden; position:absolute; left:-1000px; top:-1000">blblapx</span>
</div>
</div>
</body>
</html>
&#13;