当我在这个Angular指令中控制台输出this
时,为什么我得到和undefined
?
(function() {
'use strict';
function ExampleDirective() {
var self = this;
// returns undefined
console.log(self);
return {};
}
angular
.module('example')
.directive('exampleDirective', ExampleDirective);
})();
这只是因为指令工厂没有更新(实例化)。因此,在strict mode
this
将在non strict
模式中未定义this
将是您不想污染的全局窗口。
然而,如果您真的想用这种方式编写它,那么在提供指令工厂时,您需要自己新建并返回实例。
(function() {
'use strict';
//Accept any dependencies here
function ExampleDirective($timeout) {
var self = this;
// returns undefined
console.log(self);
this.restrict = 'AE';
this.templateUrl = "MyTemplate.html";
this.link = function(scope, elm, attrs){
}
}
ExampleDirective.factory = function () {
//Create factory function which when invoked
//angular will return newed up instance passing the timeout argument
var directive = function ($timeout) { return new ExampleDirective($timeout); };
//directive's injection list
directive.$inject = ['$timeout'];
return directive;
};
angular
.module('example')
.directive('exampleDirective', ExampleDirective.factory());
})();
虽然在用typescript编写指令时可以使用这种技术,但这可能有些过头了。正如@pankajparkar在评论中提到的,你可以使用一个控制器并将其与指令关联。控制器被实例化(newed up),并且this
将指向控制器实例本身。