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.
我在单页上有两个控制器。出于某种原因,其中只有一个一次工作。那就是我评论下面的div。然后上面的一个工作,反之亦然。
index.html
的index.html
<div ng-controller="MessageController as ctrl">
{{ctrl.messages}}
</div>
<div ng-controller="CommentController as ctrl">
{{ctrl.comments}}
</div>
app.js
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
这里是插件http://plnkr.co/edit/BXzj9GeP88BQeIA3UTWN?p=preview
1 个解决方案
#1
4
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.
你的问题是,这是否正在泄漏到全球范围。如果在声明前面加上var关键字,它将驻留在每个控制器构造函数的词法范围内。
app.controller('CommentController', ['$http', '$scope', function ($http) {
var $this = this;
$http.get(prefix + '/posts/2').success(function (response) {
$this.comments = response;
return response;
});
}]);
#1
4
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.
你的问题是,这是否正在泄漏到全球范围。如果在声明前面加上var关键字,它将驻留在每个控制器构造函数的词法范围内。
app.controller('CommentController', ['$http', '$scope', function ($http) {
var $this = this;
$http.get(prefix + '/posts/2').success(function (response) {
$this.comments = response;
return response;
});
}]);