繁体   English   中英

如何在ES6样式的角度控制器中访问范围变量?

[英]How to access scope variable in ES6 styled Angular Controller?

我在我的新Angular项目中转而使用ES6(Babel)。 ES6类不能有变量。 我如何设置我的$ scope变量?

说我有一个简单的控制器:

class MainController {
    constructor ($timeout, events) {
        'ngInject';

            this.textMaker = "Hello!" //Option #1


    } // constructor

    textMaker(){            //Option #2
        return "Hello!";
    }


} 


export default MainController;

我的html看起来像(在构建过程中控制器是自动注入的,比方说):

<h1> {{textMaker}}</h1>

选项#1和选项#2似乎都不起作用。 我得到一个空白的标题。 这么简单的事情......我做错了什么?

为控制器的属性赋值时,必须使用控制器的controllerAs语法。

  1. routerAs在路由器或指令中:

    controllerAs: 'mainCtrl' // in router or in directive, you still need to state the controller property

  2. ngController中的controllerAs:

    <div ng-controller="MainController as mainCtrl">

获取HTML中的属性:

<h1> {{mainCtrl.textMaker}}</h1>

如果要使用$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:

<h1> {{textMaker}}</h1>

让我们对上面的答案进行一点讨论,对于你拥有的ES6控制器类,你可以创建可以通过绑定更改值的函数。

例:

class something{
 constructor(){
  this._Name = '';
 }
whatIsTheName(){
 this._Name = 'Unix Rox!'
}
export default something;
}

然后你只需在click事件上调用whatIsTheName(),这是从你的所有代码中删除$ scope的好方法,如果你仍然在角度1上,它也会使你转换为Angular 2更好。

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM