javascript 内部函数中的数组长度不同

yftpprvb  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(154)

我创建了一个自定义指令。现在我从chips-break属性传递字符串数据,并将其转换为link方法中的数组。它可以工作,但当我在ng-keydown方法中获取数组长度时,它就不同了。

HTML格式

  1. <input-chips chips-break="32, 13, 188" style="width:80%"></input-chips>

字符串

JS

  1. var app = angular.module("myApp", []);
  2. app.directive("inputChips", inputChipsFun);
  3. function inputChipsFun(){
  4. return{
  5. restrict : 'EA',
  6. scope : {
  7. chipsBreak : "@"
  8. },
  9. template: '<div class="chips"><div class="chips-item"></div><input type="text" ng-keydown="inputKeyDown($event, false)"/></div>',
  10. link : function(scope, elem, attr){
  11. scope.chipsBreak = scope.chipsBreak.split(",");
  12. console.log("Length of Chips Break First Time = "+scope.chipsBreak.length);
  13. scope.inputKeyDown = function($event, is_blur){
  14. console.log("Length of Chips Break Key Press = " + scope.chipsBreak.length);
  15. }
  16. }
  17. };
  18. }


链接:https://plnkr.co/edit/RpDwaqjS81DZlZFEzdj2?p=preview
打开检查元素控制台并键入一些东西,看看有什么不同。

8gsdolmq

8gsdolmq1#

当你使用'@'时,它会得到一个字符串,这就是为什么你得到length == 11,因为你得到的是'32, 13, 188'字符串中的字符数。
查看此帖子以了解更多细节:What is the difference between '@' and '=' in directive scope in AngularJS?

  1. link : function(scope, elem, attr){
  2. var x = scope.chipsBreak.split(",");
  3. console.log("Length of Chips Break First Time = "+scope.chipsBreak.length);
  4. scope.inputKeyDown = function($event, is_blur){
  5. console.log("Length of Chips Break Key Press = " + x.length);
  6. }
  7. }

字符串
如果你执行scope.chipsBreak = scope.chipsBreak.split(","),你的scope.inputKeyDown(这是一个函数)将得到scope.chipsBreak的初始值,这是一个字符串。

相关问题