How to transfer elements to angular $ scope.array?

I'm doing something wrong, but I can't see what (it might have something to do with 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 great with two images that I already have in my array (fot_1.jpg, fot_2.jpg). The problem is the cycle. How do I go about increasing the number of elements in my array?

+3


source to share


3 answers


Just push the array into the area. angular will then update the view.



for(var i=0; i<5; i++) {
    $scope.fotografia.push({
        path: 'img/fotografia/fot_'+[i]+'.jpg'
    });
}

      

+6


source


fotografia

is a property of an object $scope

, so you would do something like:



for(var i=0; i<5; i++) {
        $scope.fotografia.push({
            path: 'img/fotografia/fot_'+[i]+'.jpg'
        });
    }

      

+1


source


Angular will update the view when everything in scope is changed or you are using $scope.digest()

. so just insert elements into the array in scope, remove fotografia = [];

because you don't need it. just:

``,

myApp.controller('homeController', function($scope) {
    $scope.fotografia = [
        {path:'img/fotografia/fot_1.jpg'},
        {path:'img/fotografia/fot_2.jpg'}
    ];
    for(var i=0; i<5; i++) {
        $scope.fotografia.push({
            path: 'img/fotografia/fot_'+[i]+'.jpg'
        });
    }
});

      

``,

+1


source







All Articles