简体   繁体   中英

Angular js multiple controller on single page with $this

I have two controllers on single page. For some reason only one of them works at a time. That is if I comment the lower div. Then upper one works and vice-versa.

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;
    });

}]);

Here's plucker http://plnkr.co/edit/BXzj9GeP88BQeIA3UTWN?p=preview

You're issue is that $this is leaking onto the global scope. If you prefix the declaration with the var keyword it will reside on each controller constructors lexical scope.

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

}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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