Fima Taf Fima Taf - 4 months ago 10
AngularJS Question

How to do if statment in AngularJS controller

I have an angular controller, in which i have a function that should return an image depends on the json that is received from the server.
The problem is that it does not matter which country is received it load only the first one (usa.png in my case).



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

<img ng-src="{{img}}"/>




Answer

You aren't doing equality:

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

Should be:

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

Or you can have strict equality (recommended):

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

Strict equality is good (in most cases), because it means, things like '1' === 1 don't return true, where as '1' == 1 would return true.