从Angular指令获取输入字段的值

时间:2014-01-22 03:24:40

标签: javascript angularjs

我在this answer中使用指令在输入字段中按下回车键时运行一个函数。

如何将输入字段element.val()的值传递给指令调用的函数?或者将输入字段element传递给函数,以便在检索后清除该值。

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

2 个答案:

答案 0 :(得分:3)

你可以这样做:

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

让控制器处理值逻辑。请参阅下面的代码。的 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();
        }
      });
    }
  };
});

答案 1 :(得分:-1)

你试过ng-submit吗?我已经创建了一个小提琴,向您展示如何在不需要您自己的指令的情况下完成您的工作。

http://jsfiddle.net/a6k7g/

显然,这个答案取决于您的要求和形式的复杂性。