Fima Taf
Fima Taf

Reputation: 977

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}}"/>

Upvotes: 0

Views: 39

Answers (3)

Hardik Vaghani
Hardik Vaghani

Reputation: 2173

You can use as this way if countries are already fixed from particular group of countries and comparing is not compulsory.

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

Regards.

Upvotes: 0

Antipod
Antipod

Reputation: 1643

You assign value, but you have to check it:

$scope.returnedUser.country == "USA"

Upvotes: 1

Callum Linington
Callum Linington

Reputation: 14417

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.

Upvotes: 6

Related Questions