AngularTS - $ scope。$ apply导致控制器停止加载

时间:2016-02-17 15:38:19

标签: angularjs typescript

每当我运行应用程序时,角度{{}}都会停留。如果我删除$ scope。$ apply括号消失并显示正确的值。

我正在使用Angular + Typescript。

控制器:

module Application.Controllers {
export class TestController {

    public hello: string = "hello";

    private scope: any;

    constructor($scope: ng.IScope) {

        this.scope = $scope;
        this.scope.hello = "Hi";
        this.scope.$apply();

        alert('no errors');

    }

}

}

控制器定义(在应用程序加载后几秒内的初始化函数中):

var appController2 = AppModule.controller("TestCTRL", ["$scope", Application.Controllers.TestController]);

观点:

    <div ng-controller="TestCTRL as t">
        <div>{{ t.hello }} {{ 1 - 1 }}</div>
    </div>

我没有看到“Hello 0”,而是看到{{t.hello}} {{1 - 1}}

如果我删除了this.scope。$ apply call,它可以工作,但它显示你好而不是hi。

我正在使用IE 11,Angular 1.4.9

我的DOM中还有另外两个工作控制器,每当它到达这个控制器时它会停止,除非我删除$ scope。$ apply

1 个答案:

答案 0 :(得分:0)

您有两个hello字段:一个是控制器的字段,其值为“hello”,在视图中使用{{ t.hello }},另一个是范围的字段,其中值为“hi”,可在视图中使用{{ hello }},或者,因为您使用{{ t.scope.hello }}将范围存储在控制器的字段中。

如果您想要一个字段,请使用

this.hello = "Hi";

而不是

this.scope.hello = "Hi";

使用controllerAs时,通常不会在范围中存储任何内容。大多数时候,你甚至不需要范围。

相关问题