这是代表我的问题的小提琴: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';
}]
}
}])
基本上,控制器没有名称,因为它是一个内联控制器,那么如何在template属性中表示它呢?我是否必须像下面这样实际声明控制器?
.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'
}
我认为您想在控制器中获取$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';
}]
}
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句