Javascript 如何将项目推入有角度的 $scope.array?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29730312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:52:19  来源:igfitidea点击:

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

javascriptangularjsfor-loop

提问by Baki

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:

我做错了但我看不到什么(这可能是由于我的 AngularJS 技能低)。我的 HTML 中有一个简单的 ng-repeat:

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

and here is my app.js:

这是我的 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?

Ng-repeat 可以很好地处理阵列中已有的 2 张图像(fot_1.jpg、fot_2.jpg)。循环是问题所在。如何将更多项目推送到我的数组中?

回答by user1777136

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

只需将它们推到范围内的阵列上即可。然后 angular 将更新视图。

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

回答by Adi

fotografiais a property of the $scopeobject, so you would do something like:

fotografia$scope对象的属性,因此您可以执行以下操作:

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

回答by Mrluobo

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:

当范围内的所有内容发生更改或您使用 $scope.digest(). 所以只需将项目推入范围内的数组,删除 fotografia = [];因为你不需要它。像这样:

```

``

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

```

``