2016-08-04 68 views
0

我有一個角度控制器,其中我有一個應該返回圖像的函數取決於從服務器接收的json。 問題是無論哪個國家收到它只加載第一個國家(usa.png在我的情況)。如何在AngularJS控制器中聲明

$scope.getUser = function(){ 
 
\t \t url = "/get"; 
 
\t \t $scope.img = ""; 
 
\t \t $http.post(url, { 
 
\t \t \t "Id":$scope.Id, 
 
\t \t \t "name":$scope.name 
 
\t \t }).then(
 
\t \t \t \t function (response){ 
 
\t \t \t \t $scope.returnedUser = response.data; 
 
\t \t \t \t if ($scope.returnedUser.country = "USA"){ 
 
\t \t \t \t \t $scope.img = "/base_icons/usa.png"; 
 
\t \t \t \t } else if ($scope.returnedUser.country = "Canada"){ 
 
\t \t \t \t \t $scope.img = "/base_icons/canada.png"; 
 
\t \t \t \t } else if ($scope.returnedUser.country = "Mexico"){ 
 
        $scope.img = "/base_icons/mexico.png"; 
 
       } 
 
\t \t \t \t }, $scope.negativeMessage);};
<img ng-src="{{img}}"/>

回答

6

你不這樣做的平等:

if ($scope.returnedUser.country = "USA") // this is an assignment operator in if 

應該是:

if ($scope.returnedUser.country == "USA") 

或者你可以有嚴格的平等(推薦):

if ($scope.returnedUser.country === "USA") 

嚴格平等是好的(在大多數情況下),因爲這意味着,像'1' === 1這樣的東西不會返回true,其中'1' == 1將返回true。

+0

不能相信這是我的錯誤,我認爲它更復雜一些,謝謝! –

+0

它碰巧是我們最好的隊友,不用擔心! –

1

您指定的值,但你要檢查一下:

$ scope.returnedUser.country ==「USA」

0

您可以按這種方式使用,如果國家已經從特定組固定的國家和比較不是強制性的。

$scope.image_base = "/base_icons/"; 
$scope.returnedUser = response.data; 
$scope.img = $scope.image_base + ($scope.returnedUser.country).toLowerCase() + ".png"; 

問候。