如何在AngularJS控制器中进行判断

Fim*_*Taf 0 javascript angularjs

我有一个角度控制器,其中我有一个应该返回图像的函数取决于从服务器接收的json.问题是收到哪个国家并不重要只加载第一个国家(在我的情况下是usa.png).

$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);};
Run Code Online (Sandbox Code Playgroud)
<img ng-src="{{img}}"/>
Run Code Online (Sandbox Code Playgroud)

Cal*_*ton 6

你没有做平等:

if ($scope.returnedUser.country = "USA") // this is an assignment operator in if
Run Code Online (Sandbox Code Playgroud)

应该:

if ($scope.returnedUser.country == "USA")
Run Code Online (Sandbox Code Playgroud)

或者你可以有严格的平等(推荐):

if ($scope.returnedUser.country === "USA")
Run Code Online (Sandbox Code Playgroud)

严格的平等是好的(在大多数情况下),因为它意味着,像'1' === 1不返回true,'1' == 1返回true的地方.