我在单页上有两个控制器。出于某种原因,其中只有一个一次工作。那就是我评论下面的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;
});
}]);
答案 0 :(得分:4)
你的问题是,这是否正在泄漏到全球范围。如果在声明前面加上var关键字,它将驻留在每个控制器构造函数的词法范围内。
app.controller('CommentController', ['$http', '$scope', function ($http) {
var $this = this;
$http.get(prefix + '/posts/2').success(function (response) {
$this.comments = response;
return response;
});
}]);