内部函数的数组长度不同

问题描述 投票:0回答:1

我制定了一个自定义指令。现在,我从

chips-break
属性传递字符串数据,并从
link
方法将其转换为数组。它有效,但是当我在
ng-keydown
方法中获取数组长度时,它是不同的。

HTML

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

JS

var app = angular.module("myApp", []);
app.directive("inputChips", inputChipsFun);

function inputChipsFun(){
  return{
    restrict : 'EA',
    scope : {
      chipsBreak : "@"
    },
    template: '<div class="chips"><div class="chips-item"></div><input type="text" ng-keydown="inputKeyDown($event, false)"/></div>',
    link : function(scope, elem, attr){
      scope.chipsBreak = scope.chipsBreak.split(",");
      console.log("Length of Chips Break First Time = "+scope.chipsBreak.length);
      
      scope.inputKeyDown = function($event, is_blur){
        console.log("Length of Chips Break Key Press = " + scope.chipsBreak.length);
      }
    }
  };
}

请参阅此链接:https://plnkr.co/edit/RpDwaqjS81DZlZFEzdj2?p=preview

打开检查元素控制台并输入一些内容并查看差异。

javascript angularjs angularjs-directive
1个回答
1
投票

当您使用“@”时,它将获得一个字符串,这就是为什么您获得 length == 11,因为您获得了“32,13,188”字符串中的字符数。

查看这篇文章了解更多详情 AngularJS 指令范围内的“@”和“=”有什么区别?

编辑:

    link : function(scope, elem, attr){
      var x = scope.chipsBreak.split(",");
      console.log("Length of Chips Break First Time = "+scope.chipsBreak.length);

      scope.inputKeyDown = function($event, is_blur){
        console.log("Length of Chips Break Key Press = " + x.length);
      }
    }

如果你这样做

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

© www.soinside.com 2019 - 2024. All rights reserved.