【问题标题】:How to access scope variable in ES6 styled Angular Controller?如何在 ES6 风格的 Angular 控制器中访问范围变量?
【发布时间】:2015-12-24 20:21:32
【问题描述】:

我在我的新 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 似乎都不起作用。我得到一个空白标题。这么简单的事情..我做错了什么?

【问题讨论】:

  • this 仅在您为控制器定义 controllerAsas 时才有效,另一方面,您可以尝试注入 $scope 并执行类似 this.$scope.whatever 的操作(我'我不确定)
  • 我在我的 ui-router 文件中定义了一个controllerAs。它的价值应该是多少?它是如何影响这一点的?
  • 好像有误会。您使用 ES6 的事实并没有改变任何东西。使用 $scope 的方式与在 ES5 中使用它的方式相同。 ES6“类”只是语法糖(还),而不是一个新特性。
  • 不,你不能在 es6 中使用 $scope,因为如果你注入并开始使用 $scope,gulp 会抛出“参数冲突”错误。这是因为,在 ES6 中,'this' 充当 $scope,但仅当您在该控制器的路由状态定义中具有控制器的 alise 时。

标签: javascript angularjs ecmascript-6 ecmascript-harmony angular-controller


【解决方案1】:

让我们稍微解释一下上面的答案,对于您拥有的 ES6 控制器类,您可以创建可以通过绑定更改值的函数。

例子:

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

然后您只需在单击事件上调用 whatIsTheName(),这是从所有代码中删除 $scope 的好方法,如果您仍在使用 Angular 1,它还可以使您更好地转换到 Angular 2。

干杯

【讨论】:

    【解决方案2】:

    当你给控制器的一个属性赋值时,你必须使用控制器的controllerAs语法。

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

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

    2. controllerAs in ngController:

      &lt;div ng-controller="MainController as mainCtrl"&gt;

    获取 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>
    

    【讨论】:

    • 我的问题是没有在模板中说明控制器。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多