Edit : corrected the foo method.
我是angularJS的大三学生,我正在努力解决这个问题。 我正在使用一个带有原型方法的指令,我想在其中一个内部发出一个偶数,但到目前为止我还没能使它工作。
angular.module('myModule')
.directive('myDirective', function () {
return {
transclude: true,
scope: {
},
bindToController: true,
controller: MyController,
controllerAs: 'myCtrl',
templateUrl: 'template/myTemplate.html'
};
}
);
然后我有一个看起来像这样的控制器。
var MyController= (function () {
function MyController($mdComponentRegistry, $attrs, $log,$scope) {
this.$scope = $scope;
this.$mdComponentRegistry = $mdComponentRegistry;
this.$attrs = $attrs;
this.$log = $log;
this.steps = [];
this.currentStep;
}
MyController.prototype.foo = function () {
this.$scope.$emit('fooEvent');
});
看起来我搞砸了$ scope注入,因为它没有被定义。
有谁能告诉我我做错了什么?非常感谢!
答案 0 :(得分:1)
您在构造函数中定义了this.$scope = $scope;
,因此您还应该将范围作为实例属性访问:
this.$scope.$emit('fooEvent');
答案 1 :(得分:0)
对于它的价值,下面是一个如何将控制器编写为类的示例:
class MyController {
constructor($mdComponentRegistry, $attrs, $log,$scope) {
this.$scope = $scope;
this.$mdComponentRegistry = $mdComponentRegistry;
this.$attrs = $attrs;
this.$log = $log;
}
$onInit() {
this.hello = 'hello';
this.currentStep;
this.foo();
}
foo() {
console.log("Executing foo function");
console.log(this.$scope.myCtrl.hello);
console.log("$emit is a", typeof this.$scope.$emit);
}
}
MyController.$inject = ['$mdComponentRegistry', '$attrs', '$log', '$scope'];
angular.module('myModule',[])
.directive('myDirective', function () {
return {
scope: {
},
bindToController: true,
controller: MyController,
controllerAs: 'myCtrl',
template:
`<fieldset>myDirective {{myCtrl.hello}}
</fieldset>`
};
}
)
.value('$mdComponentRegistry', {})
&#13;
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myModule">
<h2>Controller Written as a Class</h2>
<my-directive></my-directive>
</body>
&#13;