Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  147] [ 7]  / answers: 1 / hits: 12603  / 11 Years ago, wed, january 22, 2014, 12:00:00

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

More From » angularjs

 Answers
19

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

[#48466] Tuesday, January 21, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;