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

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

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

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

最佳答案 你可以这样做:

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