Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push items into an angular $scope.array?

I'm doing something wrong yet I cannot see what (this is probably due to my low AngularJS skills). I have a simple ng-repeat in my HTML:

<ul>
  <li ng-repeat="fot in fotografia"><img src="{{fot.path}}"></li>
</ul>

and here is my app.js:

myApp.controller('homeController', function($scope) {
    // fotografia = []; is here only because I get an error otherwise,
    // which means my later for loop can't access the $scope.fotografia

    fotografia = [];
    $scope.fotografia = [
        {path:'img/fotografia/fot_1.jpg'},
        {path:'img/fotografia/fot_2.jpg'}
    ];

    // I want to add more images with this:
    for(var i=0; i<5; i++) {
        fotografia.push({
            path: 'img/fotografia/fot_'+[i]+'.jpg'
        });
    }
});

Ng-repeat works fine with the 2 images I already have in my array (fot_1.jpg, fot_2.jpg). The loop is the the problem. How do I go about pushing more items into my array?

like image 308
Baki Avatar asked Dec 08 '25 05:12

Baki


1 Answers

Just push them onto the array in the scope. angular will then update the view.

for(var i=0; i<5; i++) {
    $scope.fotografia.push({
        path: 'img/fotografia/fot_'+[i]+'.jpg'
    });
}
like image 55
user1777136 Avatar answered Dec 10 '25 18:12

user1777136



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!