[英]How to access scope variable in ES6 styled Angular Controller?
I switched to using ES6 (Babel) in my new Angular project. 我在我的新Angular项目中转而使用ES6(Babel)。 ES6 classes cannot have variables. ES6类不能有变量。 How do I set my $scope variable now?? 我如何设置我的$ scope变量?
Say I have a simple controller: 说我有一个简单的控制器:
class MainController {
constructor ($timeout, events) {
'ngInject';
this.textMaker = "Hello!" //Option #1
} // constructor
textMaker(){ //Option #2
return "Hello!";
}
}
export default MainController;
My html looks like (controller is aut0matically injected during build, say): 我的html看起来像(在构建过程中控制器是自动注入的,比方说):
<h1> {{textMaker}}</h1>
Both Option #1 and Option#2 don't seem to work. 选项#1和选项#2似乎都不起作用。 I get a blank heading. 我得到一个空白的标题。 Such a simple thing.. what am i doing wrong? 这么简单的事情......我做错了什么?
When you assign a value to a property of the controller, you have to use the controllerAs syntax for the controller. 为控制器的属性赋值时,必须使用控制器的controllerAs语法。
controllerAs in router or directive: routerAs在路由器或指令中:
controllerAs: 'mainCtrl' // in router or in directive, you still need to state the controller property
controllerAs in ngController: ngController中的controllerAs:
<div ng-controller="MainController as mainCtrl">
Get the property in the HTML: 获取HTML中的属性:
<h1> {{mainCtrl.textMaker}}</h1>
If you want to use $scope
, inject it normally, and don't use controllerAs
: 如果要使用$scope
,请正常注入,不要使用controllerAs
:
constructor ($scope, $timeout, events) {
this.$scope = $scope; // assign $scope to a property of the controller, so it will be available in methods
this.$scope.prop = 'value'; // refer to properties on the scope in the constructor or methods
}
Html: HTML:
<h1> {{textMaker}}</h1>
Lets ellobrate a little on the answer above, for the ES6 controller class that you have, you can make functions that can change the values with binding. 让我们对上面的答案进行一点讨论,对于你拥有的ES6控制器类,你可以创建可以通过绑定更改值的函数。
Example: 例:
class something{
constructor(){
this._Name = '';
}
whatIsTheName(){
this._Name = 'Unix Rox!'
}
export default something;
}
Then you just simply call whatIsTheName() on a click event, this is a great way to remove the $scope from all your code, it also makes your conversion to Angular 2 better if you are still on angular 1. 然后你只需在click事件上调用whatIsTheName(),这是从你的所有代码中删除$ scope的好方法,如果你仍然在角度1上,它也会使你转换为Angular 2更好。
Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.