ES6 玩得很好.. 如何在没有 controllerAs 的情况下在 angular 指令中使用 this.someFunction()?
ES6 play nice.. How to use this.someFunction() inside angular directive without controllerAs?
以在 Chrome 和 Firefox 中运行良好的 Angular 指令为例:
// using Angular v1.4.8
myApp.directive('myDir', function(){
return {
restrict: 'E',
templateUrl: 'directive/myDir/myDir.html',
bindToController: true,
controllerAs: 'mydir',
controller: function($scope){
var thisdir = this;
// Using ES6 arrow functions
thisdir.shoutOut = () => {
console.log("Shouting out!");
}
}
}
});
现在在 IE11 上会抛出一个语法箭头,因为浏览器不识别箭头函数。但是,我仍然可以使用:
function shoutOut(){
console.log("Shouting out!");
}
但我希望能够在我的指令中使用 var thisdir = this
。为了代码的简洁,我也想避免在我的指令中使用 $scope
。最终我的指令将依赖于彼此以创建更大的 directive/component,这就是为什么我想使用 var thisdir = this
.
那么如何在保持与旧版浏览器的语法兼容性的同时实现这一目标呢?如果您看到更简洁的方法来解决这个问题,请告诉我!
替换
thisdir.shoutOut = () => {
console.log("Shouting out!");
}
相当于 ES5:
thisdir.shoutOut = function() {
console.log("Shouting out!");
};
或者使用像 Babel 这样的编译器将你的 ES6 代码转换为 ES5 代码。
以在 Chrome 和 Firefox 中运行良好的 Angular 指令为例:
// using Angular v1.4.8
myApp.directive('myDir', function(){
return {
restrict: 'E',
templateUrl: 'directive/myDir/myDir.html',
bindToController: true,
controllerAs: 'mydir',
controller: function($scope){
var thisdir = this;
// Using ES6 arrow functions
thisdir.shoutOut = () => {
console.log("Shouting out!");
}
}
}
});
现在在 IE11 上会抛出一个语法箭头,因为浏览器不识别箭头函数。但是,我仍然可以使用:
function shoutOut(){
console.log("Shouting out!");
}
但我希望能够在我的指令中使用 var thisdir = this
。为了代码的简洁,我也想避免在我的指令中使用 $scope
。最终我的指令将依赖于彼此以创建更大的 directive/component,这就是为什么我想使用 var thisdir = this
.
那么如何在保持与旧版浏览器的语法兼容性的同时实现这一目标呢?如果您看到更简洁的方法来解决这个问题,请告诉我!
替换
thisdir.shoutOut = () => {
console.log("Shouting out!");
}
相当于 ES5:
thisdir.shoutOut = function() {
console.log("Shouting out!");
};
或者使用像 Babel 这样的编译器将你的 ES6 代码转换为 ES5 代码。