Reputation: 1641
Ok i have the following angular js code. What im trying to do is to set some scopes to null when enter button is pressed inside a form. So far I have div with ng-click event that sets these scopes to null, but i want to make the same with enter key also.
App directive:
app.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
//access scopes here like that
//$scope.eurval = null;
//$scope.usdval = null;
//$scope.otherval = null;
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
App.controller
app.controller('formCtrl', function($scope) {
$scope.eurval = null;
$scope.usdval = null;
$scope.otherval = null;
});
Upvotes: 0
Views: 231
Reputation: 4385
Have a method that will do that for you:
app.controller('formCtrl', function($scope) {
$scope.reset = function() {
$scope.eurval = null;
$scope.usdval = null;
$scope.otherval = null;
};
$scope.reset();
});
Then use it inside the directive:
if(event.which === 13) {
scope.$apply(function (){
scope.reset();
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
Upvotes: 1
Reputation: 353
In your html file, if your directive is inside the controller, it (by default) inherits the scope from the controller. Something like this -
<div ng-controller="myCtrl">
<input my-directive type="text">
</div>
Then, you can access the controller's scope within the directive using the passed in variable, in your case scope
, and not $scope
.
Here's an article detailing the different kinds of directive scope.
Upvotes: 0