In angularJS, when trying to assign a scope variable from the value of another scope variable, the value of the derived variable is empty. In the example, I'd like to have a scope reference for the car, and also for a specific car part (which may change later in the application).
Example:
$scope.car = Car.get(); //async http service that returns a JSON car object
$scope.selectedCarPart = $scope.car.brakes;
HTML:
<div>{{car.engine}} - {{selectedCarPart}}</div>
Output:
v8 -
Why is selectedCarPart empty?
3 Answers 3
I assume that you get call is async, so when you assign the selectedCarPart, your $scope.car is currently null and doesn't have yet some brakes.
You have to wait the end of your get call and assign the value of the resulting JSON car object in the success callback of your http service.
3 Comments
Accepted answer from Apercu is correct. You can also use more general solution which is using $watch. In that case you write this:
$scope.$watch('car',function(newValue) {
$scope.selectedCarPart = newValue['brakes'];
}, true);
More information about $watch can be found here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope
Comments
Even if that would work, I think there's a better way.
<div>{{car.engine}} - {{car[selectedPartKey]}}</div>
That way, you can just change the value of selectedPartKey to 'brakes'. Your way, if car's values change, it won't be reflected...