nathancahill
nathancahill

Reputation: 10850

Get value of input field from Angular directive

I'm using the directive from this answer to run a function when the enter key is pressed in an input field.

How can I pass the value of the input field element.val() to the function the directive calls? Or pass the input field element to the function, to clear the value after it's retrieved.

HTML

<input type="text" ng-enter="newField()" />

JS

app.directive('ngEnter', function() {
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
            if(event.which === 13) {
                element.val(); // value of input field

                scope.$apply(function(){
                    scope.$eval(attrs.ngEnter); // passed to this function
                });

                event.preventDefault();
            }
        });
    };
});

Upvotes: 4

Views: 12627

Answers (2)

m59
m59

Reputation: 43785

You could just do this:

var func = scope.$eval(attrs.ngEnter);
func();

and have the controller take care of the value logic. See the code below. Live demo (click).

Also, I don't recommend prefixing your custom directives with ng. I suggest coming up with your own prefix as a namespace. ng is for Angular's core. In my examples, I am using my-enter rather than ng-enter.

Sample markup:

  <input 
    type="text" 
    ng-model="foo" 
    my-enter="myFunc"
    placeholder="Type stuff!"
  >
  <p ng-repeat="val in cachedVals track by $index">{{val}}</p>

JavaScript:

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.cachedVals = [];
  $scope.foo = '';
  $scope.myFunc = function() {
    $scope.cachedVals.push($scope.foo);
    $scope.foo = '';
  };
});

app.directive('myEnter', function() {
  return function(scope, element, attrs) {
    element.bind("keydown keypress", function(event) {
      if(event.which === 13) {
        scope.$apply(function(){
          var func = scope.$eval(attrs.myEnter);
          func();
        });
        event.preventDefault();
      }
    });
  };
});

Here's an example with an isolated scope - you don't need to $eval.

app.directive('myEnter', function() {
  return {
    scope: {
      func: '=myEnter'
    },
    link: function(scope, element, attrs) {
      element.bind("keydown keypress", function(event) {
        if(event.which === 13) {  
          scope.$apply(function(){
            scope.func();
          });  
          event.preventDefault();
        }
      });
    }
  };
});

Upvotes: 3

Matt Way
Matt Way

Reputation: 33199

Have you tried ng-submit? I have created a fiddle to show you how do to what you are after without requiring your own directive.

http://jsfiddle.net/a6k7g/

Obviously this answer depends on your requirements, and the form complexity.

Upvotes: -1

Related Questions