gpt4 book ai didi

javascript - 使用 AngularJS 绑定(bind)后如何获取元素的字符串长度?

转载 作者:行者123 更新时间:2023-11-29 18:11:03 24 4
gpt4 key购买 nike

好的,我想做的是计算一个元素内的字符数,但该元素包含绑定(bind)(例如 {{data.username}}),我想在之后 发生绑定(bind)。

到目前为止,我的想法是创建一个属性指令,并且只是 .text().length 元素被传递到“链接”函数——见下文:

到目前为止,这是我的工作:

<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Counting Characters</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
</head>
<body ng-controller="TestCtrl">
<div count-chars>{{person.firstName}} {{person.lastName}}</div>
<script>
var app = angular.module('app', []);

app.controller('TestCtrl', function ($scope) {
$scope.person = {
firstName: "James",
lastName: "Smith"
};
});

app.directive('countChars', [function(){
return {
link: function(scope, elem, attrs) {
console.log(elem.text());
console.log(elem.text().length);
}
};
}]);

</script>
</body>
</html>

问题是这只在任何绑定(bind)发生之前返回字符串(此时通过 console.logss)。我想要得到的是 James Smith11 个字符,但我得到的是 {{person.firstName}} {{person.lastName}}40 个字符。

有什么想法吗?

最佳答案

你能做的最简单的事情就是将你的代码包装到 $timeout 服务中,这样它将在下一个摘要循环中执行,这意味着到那时所有的插值作业都将完成:

app.directive('countChars', ['$timeout', function($timeout) {
return {
link: function(scope, elem, attrs) {
$timeout(function() {
console.log(elem.text());
console.log(elem.text().length);
});
}
};
}]);

演示:http://plnkr.co/edit/4vkQoTPmx0gL3hOUpN0n?p=preview

关于javascript - 使用 AngularJS 绑定(bind)后如何获取元素的字符串长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27420504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com