【发布时间】:2017-07-20 14:20:25
【问题描述】:
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 注入,因为它没有定义。
谁能告诉我我做错了什么?那将不胜感激!
【问题讨论】:
-
控制器代码没有意义。什么是
StepperCtrl,它与控制器代码有什么关系? -
我建议隔离范围指令避免使用 $emit 来传达事件。而是使用表达式
&绑定来传达事件。 -
您将
MyController显示为构造函数,然后显示StepperCtrl的原型方法 - 这是一个错字吗?如果是,并且您打算使用MyController.prototype.foo,那么您可以在原型方法中执行this.$scope.$emit,因为您已经在构造函数中设置了this.$scope。