Uncaught ReferenceError: angular is not defined - AngularJS not working
Just to complement m59's correct answer, here is a working jsfiddle:
<body ng-app='myApp'>
<div>
<button my-directive>Click Me!</button>
</div>
<h1>{{2+3}}</h1>
</body>
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.
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.