2

In HTML I have this line of code:

 <input type="text" class="training-comment" placeholder="Enter comment" ng-model="content" data-ui-keypress="{13:'keypressCallback($event)'}">

And in controller this:

$scope.keypressCallback = function ($event) {
    console.log("comment is", $scope.content);
    $event.preventDefault();
};

And when I enter some text in input and press enter in console I see that $scope.content is undefined.

Why is this ?

4
  • you can use the ng-app attr in the html head, or anywhere your page, where you run the angularjs <html ng-app> Commented Mar 31, 2014 at 12:14
  • I'm using it, this is just part of code, I have several ng-shows which work and keypressCallback wouldn't be fired if error was due to that Commented Mar 31, 2014 at 12:16
  • 1
    Can you provide a minimal example in JSFiddle or plunker? Commented Mar 31, 2014 at 12:24
  • Here is minimal example, but minimal example works so the problem is probably somewhere else plnkr.co/edit/Wfsl7kscIWu7i5JXjiZy?p=preview Commented Mar 31, 2014 at 12:56

1 Answer 1

3

I put together a Plunker example here using the Angular UI and basically copying the code from the question. I then took this example and added an ng-repeat to demonstrate one of the most common issues I have seen: scope issues:

<div ng-repeat="x in collections">
  <input type="text" class="training-comment" placeholder="Enter comment"
ng-model="content" data-ui-keypress="{13:'keypressCallback($event)'}" />
  <br /><br />
</div>

You can find this updated plunker example here. Basically whenever you use an ng-repeat or any other directive that creates a new scope your model exists in that scope - not the parent or root scope. This means that your code might be working, but it is printing out the value from the wrong scope! For more information on scopes see the angular documentation here.

To use the plunker demo, type into the first input and press the enter key, the model will be updated. But, if you type into either of the other two boxes, though, the model will either not be updated or it will be undefined (if you have never typed into the first box).

Even if this isn't the exact issue, hopefully it will still help. Best of luck!

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

2 Comments

Thanks, it's probably due to that, because I've put simplified plunker version of my code and simplified version works, plnkr.co/edit/Wfsl7kscIWu7i5JXjiZy?p=preview
Yes, problem was with ng-repeat, I've solved it by changing ng-model="content" to ng-model="$parent.content"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.