0

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?

asked May 29, 2014 at 19:06
0

3 Answers 3

1

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.

answered May 29, 2014 at 19:09
Sign up to request clarification or add additional context in comments.

3 Comments

shouldn't there be an error here as well? like 'undefined has no property named brakes' or some such?
Yep, he maybe hasn't checked his console.
@Aperçu thanks, you put me on the right track. The get method accepts a callback to be executed upon completion of the request.
0

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

answered May 29, 2014 at 19:52

Comments

0

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...

answered May 29, 2014 at 19:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.