3

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?

3
  • 1
    The only way this would work is if made both fotografia and $scope.fotografia reference the same array, ie fotografia = $scope.fotografia = [], the way you have it now they reference two different arrays Commented Apr 19, 2015 at 13:16
  • you just forgot use $scope. the view is binded to $scope variables not private variables. Commented Apr 19, 2015 at 13:18
  • Moreover, even if this has no impact in your current code, but JSON standard defines that String shall be delimited by double quotes ". Your image shall be {path:"img/fotografia/fot_1.jpg"}. To solve your issue, replace fotografia by $scope.fotografia into your controller Commented Apr 19, 2015 at 13:35

3 Answers 3

8

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'
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Angular will update the view when everything in scope is changed or you use $scope.digest(). so just push items into the array in scope,remove the fotografia = []; because you don't need it. just like this:

```

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'
        });
    }
});

```

Comments

1

fotografia is a property of the $scope object, so you would do something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.