I'm attempting to learn angular and I am struggling with a simple button click.
I followed an example which has an identical code to the one below.
The result I am looking for is for the button click to cause an alert. However, there is no response to the button click. Does anybody have any ideas?
<html lang="en" ng-app="myApp" > <head> <meta charset="utf-8"> <title>My AngularJS App</title> <link rel="stylesheet" href="css/app.css"/> </head> <body> <div > <button my-directive>Click Me!</button> </div> <script> var app = angular.module('myApp',[]); app.directive('myDirective',function(){ return function(scope, element,attrs) { element.bind('click',function() {alert('click')}); }; }); </script> <h1>{{2+3}}</h1> <!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> --> <script src="lib/angular/angular.js"></script> <script src="lib/angular/angular-route.js"></script> <script src="js/app.js"></script> <script src="js/services.js"></script> <script src="js/controllers.js"></script> <script src="js/filters.js"></script> <script src="js/directives.js"></script> </body> </html>
You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular
does not exist yet. This is an error (see your dev tools console).
In this line:
var app = angular.module(`
you are attempting to access a variable called angular
. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.
<h1>{{2+3}}</h1> <!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> --> <script src="lib/angular/angular.js"></script> <script src="lib/angular/angular-route.js"></script> <script src="js/app.js"></script> <script src="js/services.js"></script> <script src="js/controllers.js"></script> <script src="js/filters.js"></script> <script src="js/directives.js"></script> <script> var app = angular.module('myApp',[]); app.directive('myDirective',function(){ return function(scope, element,attrs) { element.bind('click',function() {alert('click')}); }; }); </script>
For completeness, it is true that your directive is similar to the already existing directive ng-click
, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.
Use the ng-click
directive:
<button my-directive ng-click="alertFn()">Click Me!</button> // In <script>: app.directive('myDirective' function() { return function(scope, element, attrs) { scope.alertFn = function() { alert('click'); }; }; };
Note that you don't need my-directive
in this example, you just need something to bind alertFn
on the current scope.
Update: You also want the angular libraries loaded before your <script>
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With