Sarah cartenz Sarah cartenz - 2 months ago 4
Javascript Question

A scope variable is updated after a popup to the user but not in a certain place

I have the following initial code:

$scope.user = {'Name':'holl'};
$scope.tweet = {'message' : "Good job " + $scope.user.Name + "!! You have collected all there is..!"};

Later I call a function where user.Name is altered but $scope.tweet somehow is not altered and prints the old user name holl. I use the console to debug but the console is returning the updated name. I even use $scope.$apply() before sending the tweet (the console returns the updated version in this area) but no use. I don't understand why $scope.tweet stays the same. Any suggestions?


As per my understanding you are having a function that changes only $scope.user. But this wont change $scope.user.Name in the message of $scope.tweet because when the $scope.tweet is create the value of the user.Name is taken and converted to string and assigned to tweet.message. tweet.message won't get updated automatically.

So to solve this you have 2 options.

1) do the assignment to $scope.tweet again in the function where $scope.user is altered after the $scope.user is altered.

function X() {
    $scope.user = {'Name':'Jamie'};
    $scope.tweet = {'message' : "Good job " + $scope.user.Name + "!! You have collected all there is..!"};


2) Put $watch of $scope.user and assign the $scope.tweet inside watch function.

$scope.$watch('user', function(altered) {
    $scope.tweet = {'message' : "Good job " + altered + "!! You have collected all there is..!"};
$scope.user = {'Name':'holl'};