2015-09-27 75 views
0

我在單個頁面上有兩個控制器。出於某種原因,一次只能有一人工作。那就是如果我評論下面的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

回答

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

}]); 
+0

謝謝:)那就是它。我覺得很蠢 – ka4tik

+0

我相信你不是第一個[也不會是最後]被JavaScript範圍模型所捕獲。我建議你用你的代碼來抓這樣的東西。 – CainBot