1

*Note, the line wraps don't matter to me, I need the line number based on the number of new line characters, because I am going to split vm.text in the future and access it like an array.

I want to know what row of a text area I'm on, every time I hit the enter key. I followed the answer from here: Find out the 'line' (row) number of the cursor in a textarea

And I attempted to merge it with ng-keypress like so:

enmasse.html

<form role="form" ng-submit="vm.submit()">
<div class="form-group">
    <h2 layout="column" layout-align="center center">Multi-Event Creation</h2>
    <br>

    <div>Input Formats</div>
    <!-- display input 'rulebook' here -->
    <br>
    <md-input-container>
        <label style="color:#545454">Enter your events/tasks, line by line</label>
        <textarea cols="50" ng-keypress="vm.check(this, $event.keyCode)" ng-model="vm.text" required></textarea>
    </md-input-container>

    <div class="form-group" layout="column" layout-align="center center">
        <md-button class="md-raised md-primary btn-submit" type="submit">Submit</md-button>
    </div>

</div>

Note, I am using ngDialog to connect my controller to my form.

enmasse-controller.js

(function () {
'use strict';

angular
    .module('app.enmasse.controllers')
    .controller('EnmasseController', EnmasseController);

EnmasseController.$inject = ['$rootScope', '$scope', 'Authentication', 'Snackbar', 'Posts', 'Access'];

function EnmasseController($rootScope, $scope, Authentication, Snackbar, Posts, Access) {
    var vm = this;
    vm.submit = submit;
    vm.check = check;
    vm.lineNumber;

    function check(textarea, keyCode) {
        //console.log(keyCode); *works

// trouble in this section
        if (keyCode == 13) {
            vm.lineNumber = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
            console.log(vm.lineNumber);
        }
//

        //if (keyCode==13) {
        //console.log(vm.text); *works for pulling all text in textarea, but need to pull the previous line!
        //validate();
        //}
    }

    function submit() { //called when all the lines are validated and user clicks submit
    }
}
})();

The browser console is throwing the following error at me --> TypeError: Cannot read property 'substr' of undefined

How can I get around this?

Community
  • 1
  • 1
MMP
  • 546
  • 2
  • 5
  • 19

1 Answers1

1

That's becuase this in angular expressions is not the DOM node. You can instead pass the event:

<textarea cols="50" ng-keypress="vm.check($event, $event.keyCode)" ng-model="vm.text" required></textarea>

And set textarea to be the target of the event:

function check(event, keyCode) {
     var textarea = event.target;
     ...
}
eladcon
  • 5,815
  • 1
  • 16
  • 19