2

I make a custom directive. Now I pass string data from the chips-break attribute and convert it to an array from the link method. It works, but when I get the array length inside the ng-keydown method, it is different.

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);
      }
    }
  };
}

See this link: https://plnkr.co/edit/RpDwaqjS81DZlZFEzdj2?p=preview

Open inspect element console and type some things and see the difference.

1 Answer 1

1

When you use '@' it will get a string so that's why you get length == 11 because you are getting character count in '32, 13, 188' string.

Check this post for more details: What is the difference between '@' and '=' in directive scope in 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);
  }
}

If you'll do scope.chipsBreak = scope.chipsBreak.split(",") your scope.inputKeyDown (which is a function) will get initial value of scope.chipsBreak which is a string.

Sign up to request clarification or add additional context in comments.

1 Comment

yes @Chrish but I convert string into Array so why it's treat as string in inner function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.