As I delve into learning angular, custom directives have presented me with a challenge that has left me stumped. Below are the custom directives in question:
/**
* Created by Lucas on 11/06/2015.
*/
'use strict'
eventsApp
.directive('greeting',function() {
return {
restrict: 'E',
replace: true,
template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
controller: function GreetingController($scope) {
var greetings = ['hello'];
$scope.sayHello = function() {
alert(greetings.join());
}
this.addGreeting = function(greeting) {
greetings.push(greeting);
}
}
};
})
.directive('finnish',function() {
return {
restrict: 'A',
require: 'greeting',
link: function(scope, element, attrs, controller) {
controller.addGreeting('hei');
}
}
})
.directive('hindi',function() {
return {
restrict: 'A',
require: 'greeting',
link: function(scope, element, attrs, controller) {
controller.addGreeting('नमस्ते');
}
}
});
Although these directives are functioning as expected, trouble arises when the greeting
controller is modified to accept an external controller via an attribute like so:
.directive('greeting',function() {
return {
restrict: 'E',
replace: true,
template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
controller: '@',
name: 'ctrl'
};
})
This adjustment would necessitate references in the HTML code as follows:
<!DOCTYPE html>
<html ng-app="eventsApp">
<head lang="en">
<meta charset="UTF-8>
<title>Event Registration</title>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/app.css"/>
<'/'body>
<greeting ctrl="GreetingController">
<div finnish hindi></div>
</greeting>
<script src="lib/jquery.min.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="lib/underscore-1.4.4.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/GreetingController.js"></script>
<script src="js/directives/greeting.js"></script>
<script src="js/filters.js"></script>
<script src="lib/bootstrap.min.js"></script>
<'/'body>
</'/html>
The moment these changes are made, the other directives cease working and Angular throws up the following error:
Error: [$compile:ctreq] Controller 'greeting', required by directive 'hindi', can't be found!
I am certain there must be a solution to rectify this issue, but being new to Angular, I find myself at a loss.