Get input field value from Angular directive

I use the directive this answer to run the function when the enter key is pressed in the input field.

How to pass the value of the input field of the element.val()function called by the directive? Or pass an input field elementto a function to clear the value after receiving it.

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();
            }
        });
    };
});
+4
source share
2 answers

You could just do this:

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

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

, ng. . ng Angular. my-enter, ng-enter.

:

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

- $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();
        }
      });
    }
  };
});
+3

ng-submit? , , , , .

http://jsfiddle.net/a6k7g/

, .

-1

All Articles