I'm really new to angular and I'm having an issue with scope between my directive and controller. Here is my code:
Controller:
var myApp = angular.module('myApp', []);
myApp.controller('testCtrl', function ($scope, $http) {
$scope.doSomething = function() {
alert("Testing Scope");
};
});
Directive:
myApp.directive('keyEvents', function($document) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$document.on('keypress', function(e) {
switch (e.keyCode) {
case (49):
doSomething();
break
default:
}
});
}
};
});
HTML:
<script src= "js/main.js"></script>
<script src = "js/keyevents.js"></script>
<body ng-app ="myApp">
<div ng-controller="testCtrl">
<div key-events>
</div>
</div>
</body>
I am getting this error: Uncaught ReferenceError: doSomething is not defined - how do I use the doSomething function inside my directive?
This line:
doSomething();
Should be
scope.doSomething();
Because when you define a method in a scope from a controller and this scope is inherited in a directive, you can access it only through scope
passed as an argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.