我正在学习角度,当我学习自定义指令时,我陷入了一种我不知道如何解决的情况。这是我的自定义指南:
/**
* 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('नमस्ते');
}
}
});
但是,如果我通过以下属性更改greeting
控制器以接收外部控制器,这些指令运行正常:
.directive('greeting',function() {
return {
restrict: 'E',
replace: true,
template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
controller: '@',
name: 'ctrl'
};
})
并在HTML中引用如下:
<!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"/>
</head>
<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>
其他指令停止工作,angular记录以下错误:
错误:[$ compile:ctreq]无法找到指令'hindi'所需的控制器'问候'!
我想有办法解决这个问题,但是因为我是Angular的新手,所以我有点失落。
答案 0 :(得分:2)
如果您将控制器作为属性获取,则属性名称必须是指令的名称:
<greeting greeting="GreetingController" finnish="" hindi=""></greeting>
请参阅this plunker