我正在使用 Angular 的“controller as somename”语法。
假设下面的函数是我的 Controller
function myCOntroller($scope)
{
$scope.$emit('event');
}
以上功能正常运行。我尝试过像下面这样
function myController()
{
var reference = this;
reference.$emit('event');
}
这不起作用。当我可以使用数据绑定(bind)的引用时。为什么我不能用它来做这种事情。我认为 Reference 现在拥有 $scope 拥有的所有功能。如果 $emit 以这种方式工作,这不是有意义吗?
NOTE: Sorry about the code samples. I just asked this question as a proof of concept, so don't have any real code.
最佳答案
如前所述here ,
“Controller as”是 1.2 中引入的语法糖,试图修复 $scope 的体验(至少是受到范围原型(prototype)继承不良影响的部分)。
<body ng-controller="MyCtrl as myCtrl">
...
app.controller('MyCtrl', function () {
...
});
与
相同<body ng-controller="MyCtrl">
...
app.controller('MyCtrl', function ($scope) {
$scope.myCtrl = this;
...
});
它并没有消除对作用域的需求,而是在 Controller 中引入了有用的模式(请注意,您不需要在前一个示例中注入(inject) $scope,除非您需要 $scope.$on 等)。
因此,当您希望它充当模型时,请使用 this
而不是 $scope
。
关于javascript - Angular Controller 作为语法,特殊场合还需要 $scope 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29823468/