1

I am working on an angularJS app and i found a problem that I cant solve. I have a variable with predefined text that I want to replace in an email with the actual values, it looks like this:

$scope.predefinedVars = {
    'client_name': $scope.itemPartner.name,
    'client_city': $scope.itemPartner.city,
    'client_county': $scope.itemPartner.county,
    'client_address': $scope.itemPartner.address,
    'client_phone': $scope.itemPartner.phone,
    'client_email': $scope.itemPartner.email
};

and so on...

Now later on, when I choose a partner, the itemPartner object changes the data. For example: i have a function to watch when I change the partner from a select box:

$scope.$watch('newContract.partner_id', function() {
    $scope.itemPartner = _.where($scope.listPartners, {'id': $scope.newContract.partner_id})[0];
    alert(JSON.stringify($scope.itemPartner));
});

Now, in the alert, I can see the itemPartner data has changed, but if I try to read the values from my 1st variable $scope.predefinedVars, the values are still empty and do not change.

Is there a way to force the values to change when I change the itemPartner object ?

1 Answer 1

1

The problem is that you have set the fields of your predefinedVars object to a primitive. In javascript, primitives are passed by value, not by reference (google if you're not sure what that means).

The result is that any reference to the object you used to set it originally is lost.

You have a couple of alternatives:

  1. Instead of replacing the email using the data from $scope.predefinedVars, use the data from $scope.itemPartner. This is less work.

  2. create a function that repopulates predefinedVars

e.g.

function populatePredefinedVars (partner){

  $scope.predefinedVars = {
    'client_name': partner.name,
    'client_city': partner.city,
    'client_county': partner.county,
    'client_address': partner.address,
    'client_phone': partner.phone,
    'client_email': partner.email
  };
}

$scope.$watch('newContract.partner_id', function() {
  $scope.itemPartner = _.where($scope.listPartners, {'id': $scope.newContract.partner_id})[0];
  populatePredefinedVars($scope.itemPartner);
});
Sign up to request clarification or add additional context in comments.

1 Comment

thank you veryu much Ed Hinchliffe, i implemented the 2nd choice and it is a good idea :)

Your Answer

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.