Home How to alter an array in JS file through a method call from HTML in Angular?
Reply: 1

How to alter an array in JS file through a method call from HTML in Angular?

NateH06
1#
NateH06 Published in 2017-11-14 20:47:51Z

I'm using Angular.js and trying to clear an array which is first instantiated and held on my module:

 angular.module(myApp)
  .controller('myCtrl', function ($rootScope){
    var vm = this;

    vm.myArr = ["Clear", "Me"]

    vm.clearer = function(arr) {
       arr = [];
    };

    vm.copier = function(arrToOverwrite, arrToCopy) {
        arrToOverWrite = angular.copy(arrToCopy);
   };

And I call this method from my HTML file:

    (controller myCtrl is aliased as ctrl)
    <input type="button" ng-click="ctrl.clearer(ctrl.myArr)" value="clear">

However, in the JS, it is underlining the arr, saying the value is never used. And, say I have something that always displays the value of myArr in the HTML, it is unaffected by the changes. I thought since JS is pass by reference, if myArr is passed as the reference in the clearer method, if it gets updated there, that it would then be updated with that value everywhere?

How would I go about this? I need to use the clearer method in other places on other arrays that may be held "in memory" here in the JS file at other times.

Ori Drori
2#
Ori Drori Reply to 2017-11-14 21:03:01Z

When you call the function you assign the arr param with a reference to ctrl.myArr. With the expression arr = [] you assign arr to reference an empty array, but ctrl.myArr still points to the original array.

In this case you need to mutate the array directly, by changing the length to 0, for example:

var array = [1, 2, 3];

var clearer = function(arr) {
  arr.length = 0;
};

clearer(array);

console.log(array);

If you need to remove certain items, or add new items, you can use Array#splice or angular.copy() to overwrite the array with another:

var array = [1, 2, 3, 4, 5, 6, 7];
var replacement = [9, 10, 11];

function copier(arrToOverwrite, arrToCopy) {
  arrToOverwrite.splice(0, arrToOverwrite.length, ...arrToCopy); // or angular.copy(arrToCopy, arrToOverwrite)
};

copier(array, replacement);

console.log(array);

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304503 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO