这是代表我的问题的小提琴:https://jsfiddle.net/m9t7ew8j/1/
重要的代码的基本部分如下:
.directive('firstDirective', [function () {
return {
restrict: 'E',
template: '<div>This is a directive.
Here is a scope variable
pre-defined: {{name}} </div>', // <---- this is the problem
controller: ['$q', function ($q) {
var vm = this;
vm.name = 'something';
}]
}
}])
基本上,控制器没有名称,因为它是内联控制器,所以如何在模板属性中表示它?我是否必须像下面这样声明控制器?
.controller('secondController', [function(){
var vm = this;
vm.name = 'John Snow';
}])
.directive('secondDirective', [function(){
return {
restrict: 'E',
template: '<div>This is a directive.
Here is a scope variable
pre-defined: {{vm.name}} </div>', // <- declaring as vm.name will work
controller: 'secondController as vm'
}
答案 0 :(得分:2)
我认为在您的控制器中,您希望获得$scope
并将变量分配给$scope
。
.directive('firstDirective', [function () {
return {
restrict: 'E',
template: '<div>This is a directive.
Here is a scope variable
pre-defined: {{name}} </div>',
controller: ['$scope','$q', function ($scope,$q) {
$scope.name = 'something';
}]
}
}])
演示:http://plnkr.co/edit/uzudOphRL8QO6utEBF4F?p=preview
实现使用this
.directive('firstDirective', [function () {
return {
restrict: 'E',
template: '<div>This is a directive.
Here is a scope variable
pre-defined: {{vm.name}} </div>',
controllerAs: 'vm',
controller: ['$q', function ($q) {
var vm = this;
vm.name = 'something';
}]
}
}])