0

My scope does not contain an "notYetExistingArray" at the time of generation.

Via a button, I would like to add the array plus a first entry to it. Each subsequent push of the same button should then add another entry.

Unfortunately, I have no clue on how to approach it.

Currently I have:

<button type="button" ng-click="notYetExistingArray.unshift({})">

If the scope already contains an object "notYetExistingArray" of type array = [] I can easily add an entry with above function.

Any advise on how to do it?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Nogga
  • 89
  • 2
  • 8

3 Answers3

1

Call a controller function from your ng-click directive rather than trying to do all that stuff in your markup. It can include a check for the existence of the array, and create it if needed.

<button type="button" ng-click="addThis(thing)">

In the controller:

ctrl.addThis = function(thing) {
    if (ctrl.myArray === undefined) {
        ctrl.myArray = [];
    }

    myArray.unshift(thing);
};

Note that I'm using controllerAs syntax here, so ctrl might be $scope instead.

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • This works. Any hint on how I can also define myArray as parameter to the addThis function? – Nogga Jun 08 '16 at 20:19
  • Do you mean a property or a function argument? – isherwood Jun 08 '16 at 20:21
  • Basically I want to pass the object property to be used as un-initialized array within the scope to the function as well. So function addThis("prop1.prop2", {}) should add {} to a potentially not existing scope-entry such as scope.prop1.prop2 - I am not a Javascript expert, so it is hard to explain – Nogga Jun 08 '16 at 20:43
  • I have found http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference but it seems as I am simply not able to convert that logic to my problem – Nogga Jun 08 '16 at 20:48
0

You can initialize the array before doing that, for example:

<button type="button" ng-init="notYetExistingArray=[]" ng-click="notYetExistingArray.unshift({})">

check the documentation for ng-init https://docs.angularjs.org/api/ng/directive/ngInit

arop
  • 451
  • 1
  • 5
  • 11
  • This is ok until such time as the array exists on scope at page load. Maybe better to check for its existence rather than assuming. – isherwood Jun 07 '16 at 21:12
0

A good way is to bind a function on the ngClick directive, which will perform a test in order to check if the array exist.

In your controller :

function foo(item) {
  //if my array does not exist
  if (!$scope.myArray) {
    //create the array
    $scope.myArray = [];
  }
  //Here, we can add some data to our array, we are sure that the array exist
  $scope.myArray.unshift(item);
}

$scope.foo = foo;

Html :

<h2>Array.length : {{myArray.length}}</h2>
</br>
<button type="button" ng-click="foo({})">Add</button>

Feel free to check the Working Plunker

Paul Boutes
  • 3,285
  • 2
  • 19
  • 22