1

I would like to use $parse in angularJS to dynamically create a scope variable which references an array and then push to that array; but $parse's assign method does not seem to do the trick.

$scope.life.meaning = [];

var the_string = 'life.meaning';

// Get the model
var model = $parse(the_string);

Would like to push '42' into the array. So the following won't work:

// Assigns a value to it
model.assign($scope, 42);

Are there any other ways to do this? Thanks.

2
  • $scope.life.meaning.push(42) Commented Aug 5, 2015 at 19:22
  • Thank you but it's dynamically declared so if used in a directive you would not know the value of the_string until it is declared programmatically. I just wrote $scope.life.meaning = [] so it was clear it would always reference an array. Commented Aug 5, 2015 at 19:24

1 Answer 1

4

Your example is overwriting the assignment for that object on the scope. The $parse can be used to either get or make assignments. What you need to do it get the array and then push the item onto the array that you got. Because JavaScript arrays are pointers in memory, adding to the array that you retrieved will do the trick.

//get the current value as evaluated against the $scope
var ar = $parse('life.meaning')($scope);

//if the value isn't an array then make it one
if (!Array.isArray(ar)) {
    ar = [];
    $parse('life.meaning').assign($scope, ar);
}

//add an item to the array
ar.push(42);
Sign up to request clarification or add additional context in comments.

1 Comment

Genius answer. Thanks :-D

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.