AFP_555
AFP_555

Reputation: 2608

How to reference variable from scope in AngularJS

Version: 1.5.5

I have two arrays in my scope, let's call them:

$scope.array1 = [1,2,3,4];
$scope.array2 = [5,6,7,8];

I want to modify one of this arrays based on a condition, for this I want to use the ternary conditional because I'll make changes on the array in different parts of my code, thus I'll avoid repeating the condition multiple times:

var header = (myCondition)?$scope.array1:$scope.array2;
header = [];
header.push(10);
//some code
header.push(11);

But this is not working! The changes on header are not reflected on the object in the $scope.

So I have to do this:

if(myCondition){
  $scope.array1 = [];
  $scope.array1.push(10);
}
else{
 $scope.array2 = [];
 $scope.array2.push(10);
}
//some code
if(myCondition){
 $scope.array1.push(11);
}
else{
 $scope.array2.push(11);
}

Which seems awful...

I think the first way should really work because header will keep the reference to the object in the $scope. Anyway, that was the dummy code to make my point, here is the real code (sorry if it's awful. My first time with Javascript):

$scope.getHeaders = function(type){
    req = createJsonedFilters(false, true, true);
    req['type'] = type;
    $http.post("/getHeaders", req).then(
        function(res){
            data = res.data;
            if(data['msg'] == "OK"){
                var minmax = (type == 'epidem')?"epidemMinMax":"entomoMinMax";
                var headers = (type == 'epidem')?$scope.epidemHeaders:$scope.entomoHeaders;
                headers = [];
                data_minmax = data[minmax]
                minmax_headers = Object.keys(data_minmax).sort();
                console.log(minmax_headers);
                for(var i=0; i < minmax_headers.length; i++){
                    var minmax_name = minmax_headers[i];
                    var mm_elem = data_minmax[minmax_name]
                    var atributo = {
                      name: minmax_name,
                      enabled: true,
                      slider: {minValue: parseInt(mm_elem['min']), maxValue: parseInt(mm_elem['max']),
                               options: {floor: parseInt(mm_elem['min']),ceil: parseInt(mm_elem['max']),
                               step: 1}}
                    };
                    headers.push(atributo);
                }
                console.log(headers);
                $scope.refreshAttributes();
            }
            else{
                console.log('Empty ' + type + ' Dataset...')
            }
        },
        function(){
            console.log("Couldn't load " + type + " headers...")
        }
    );
}

Any ideas why the reference to headers won't modify the object in the scope? If there is any output I can give you, comment and I'll update the question.

Upvotes: 0

Views: 92

Answers (2)

Erazihel
Erazihel

Reputation: 7605

The arrays are properties of the $scope object. You can thus access them using their key with the syntax $scope[arrayName] (where arrayName is a string).

Therefore, using myCondition, you have to store the name of the array you want to modify in a variable that you'll use in the following steps.

var arrayName = (myCondition) ? 'array1' : 'array2';
$scope[arrayName] = [];
$scope[arrayName].push(10);
//some code
$scope[arrayName].push(11);

EDIT

Your code doesn't work because you erase the reference to the $scope.array1 by creating a new array (header = []).

You could copy the content of the header array into the appropriate array of your $scope after all the operations are made.

var header = [];
header.push(10);
//some code
header.push(11);

if (myCondition) {
    $scope.array1 = header;
} else {
    $scope.array2 = header;
}

Upvotes: 2

Abhishek
Abhishek

Reputation: 1477

The reason why is was not working with the reference for headers is when you assign appropriate array via

var headers = (type == 'epidem')?$scope.epidemHeaders:$scope.entomoHeaders;

Now the headers will hold the reference for either of the $scope.epidemHeaders or $scope.entomoHeaders array(as array is also an object).

And when you try to assign the new array to headers via headers = []. The headers now holds new reference, not either of the $scope.epidemHeaders or $scope.entomoHeaders array. i.e headers will be pointing to different array, whereas say $scope.epidemHeaders = [1,2,3,4] and $scope.entomoHeaders = [5,6,7,8]

Hence pushing to headers after assigning new array wont push the element to the array on the $scope. In fact it adds to the new array. Hence the changes weren't reflected.

If you still want to use the header ways of reference, try pushing the element without setting the new array.

Or if resetting is your case then use the below mentioned way:

var headers = (type == 'epidem')?$scope.epidemHeaders:$scope.entomoHeaders;
headers.length = 0; // Trick to reset the array retaining the same reference
headers.push(11);

Upvotes: 1

Related Questions