[英]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.
那就是如果我评论下级div。 Then upper one works and vice-versa.
然后上一个工作,反之亦然。
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
You're issue is that $this is leaking onto the global scope. 您的问题是$ this正在泄漏到全局范围内。 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;
});
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.