【问题标题】:Angular js multiple controller on single page with $this带有 $this 的单个页面上的 Angular js 多个控制器
【发布时间】:2015-09-27 11:04:07
【问题描述】:

我在单个页面上有两个控制器。出于某种原因,一次只有其中一个工作。那就是如果我评论较低的div。然后上一个工作,反之亦然。

index.html

<div ng-controller="MessageController as ctrl">

{{ctrl.messages}}

</div>
<div ng-controller="CommentController as ctrl">

{{ctrl.comments}}

</div>

app.js

var app = angular.module('plunker', []);

var prefix = 'http://jsonplaceholder.typicode.com';
app.controller('MessageController', ['$http', function ($http) {

$this = this;
$http.get(prefix + '/posts/1').success(function (response) {
        $this.messages = response;
        return response;
    });
}]);

app.controller('CommentController', ['$http', '$scope', function ($http) {
    $this = this;
    $http.get(prefix + '/posts/2').success(function (response) {
        $this.comments = response;
        return response;
    });

}]);

这里是采摘者http://plnkr.co/edit/BXzj9GeP88BQeIA3UTWN?p=preview

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    您的问题是 $this 泄漏到全局范围内。如果您在声明前加上 var 关键字,它将驻留在每个控制器构造函数的词法范围内。

    app.controller('CommentController', ['$http', '$scope', function ($http) {
        var $this = this;
        $http.get(prefix + '/posts/2').success(function (response) {
            $this.comments = response;
            return response;
        });
    
    }]);
    

    【讨论】:

    • 我确定你不是第一个 [也不会是最后一个] 被 JavaScript 作用域模型捕获的。我建议你 lint 你的代码来捕捉这样的事情。
    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多