Haris Haris - 6 months ago 16
AngularJS Question

How to create array of predefined length and then add items to it in Angularjs

Following this link I am able to display number of available slot in my app but what i need is to add items to these slots on click event to the array.

Untill now I assigned the function value to an array

{{heightunit=getNumber(myNumber)}}


and then pushing element to that array but if i log the array in console, it did add item to array but in view it doesn't changes its lenght

{{heightunit.length}}


and array still display empty list

Here is some code

<div ng-repeat="(key,item) in getNumber(myNumber) track by $index" class="wrapper " >
<span class="left">{{myNumber-$index}}Unit</span>
<div id="{{myNumber-$index}}Unit" class="image" ng-show="item.length">
<img src="{{item.image}}">
</div><span class="drop-right">
<span ng:click="removeItem(key,item.entity_id)">x</span>
</span></div>


in controller

$scope.myNumber = <?php echo $instalableunits ?>;
$scope.getNumber = function(num) {
return new Array(num);
}


Now i created another array

$scope.heightunit= [];


in view assigned getNumber() value to it

{{heightunit=getNumber(myNumber)}}


and pushing value to it and logging in console, console shows data in it but it is not getting updated in view

$scope.heightunit.push($scope.addproduct[id]);

console.log($scope.heightunit);

Answer

I hope this helps,

view

{{numbers.length}}
<div ng-repeat="num in numbers"></div>

controller

app.controller("myCtrl", function($scope,$timeout) {
   $scope.numbers = [];
   $timeout(function(){
      $scope.numbers =[1,2]
   },2000);
});
Comments