How to use grid with ng-repeat in Angularjs?

Asked

Viewed 1,296 times

1

I have a mobile app I want the ng-repeat create the content in a grid as I have in the example below but always repeat as an example below:

<div class="row responsive-md">
        <div class="col">
            <a href="#/app/comer">
                <div class="img_comer">
                    <div class="texto_categorias_home">
                        <div><i class="fa-fa-cutlery"></i></div>
                        Comer
                    </div>
                </div>
            </a>
        </div>
        <div class="col">
            <a href="#/app/dormir">
                <div class="img_dormir">
                    <div class="texto_categorias_home">
                        <div><i class="fa-fa-bed"></i></div>
                        Dormir
                    </div>
                </div>
            </a>
        </div>
    </div>

In this case this manual now I want to do the same but in ng-repeat how can I do ?

View ng-repeat

<div class="row" ng-repeat="noticias in noticias_home">
        <div class="col">
            <a href="#/app/ver-noticia/{{noticias.url_artigo}}/{{noticias.id}}">
                <div style="background: url(https://www.sabeonde.pt/gtm/anexos/posts_home/{{noticias.id_anexo}}.{{noticias.tipo}}); border-top-left-radius:10px; border-top-right-radius:10px; height: 200px; background-size: 100% 100%; background-repeat: no-repeat;">
                </div>
            </a>
            <div style="border-bottom-left-radius:10px; border-bottom-right-radius:10px; height: 100px; background-color: white;">
                <table border="0" cellpadding="0" cellspacing="0">
                    <tr>
                        <td colspan="2" valign="top">
                            <a href="#/app/ver-noticia/{{noticias.url_artigo}}/{{noticias.id}}"><div style="font-size: 15px; color:black; margin:5px 0px 15px 10px;  font-weight: bold; ">{{noticias.titulo}}</div></a>
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">
                           <div ng-init="liked='Gosto'" ng-click="like({{noticias.id}})" ng-controller="LikeNoticiasHome" style="margin-left:10px;" class="botao_gosto"><i class="fa fa-heart"></i> {{liked}}</div>
                           <div id="mostra_gostos" class="mostra_gostos">{{noticias.likeCount}}</div>
                           <div ng-click="partilhar({{noticias.id}})" ng-controller="PartilhaNoticiasHome" class="botao_posts"><i class="fa fa-share-alt"></i> Partilhar</div>
                           <a href="#/app/ver-noticia/{{noticias.url_artigo}}/{{noticias.id}}"><div class="botao_posts"><i class="fa fa-search"></i> Ver +</div></a>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>

Controller

.controller('ListaNoticiasHome', function($scope, $http, $stateParams, sessionService) {
    $http.get("https://www.sabeonde.pt/api/api_noticias_home.php").success(function (data) {
        $scope.noticias_home = data; 
    });
})

3 answers

3

Example of using grid with ng-repeat in Angularjs:

<div ng-app="myApp" ng-controller="customersCtrl"> 

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function (response) {$scope.names = response.records;});
});
</script>

You can customize the elements with the use of directives.

References:

http://www.w3schools.com/angular/angular_tables.asp

https://docs.angularjs.org/guide/directive

  • You can edit and make an example based on what I have manual do for ng-repeat equal ?

  • You can pass the Javascript code using Angularjs by filling the objects, attributes, arrays of your controller?

  • I put in question the controller

2

Assuming that you first need to detect if it is a tablet or not, let’s do it through resolution, since some plugins to detect the device are not 100% reliable.

You can do this directly on app startup or any resolution resize. This code works by including resize:

$scope.$watch(function(){
    return $window.innerWidth;
}, function(value) {
    if (value < 1024) {
        $scope.mediaMobile = true;
    } else {
        $scope.mediaMobile = false;
    };
});

Note: In my case, this code is inside a controller, called mainCtrl, which is common to the whole app.

Assuming that the resolution that determines whether it is a tablet or not is the resolution less than 1024px, we can check it directly in HTML. If the resolution is lower, ie if it is a tablet, we display the grid with content.

For this you can use the ng-if or the ng-show, the difference is that ng-if will not render the html until the value true, that is, html will not exist on the page until its display is authorized. Thus:

<div ng-if="mediaMobile">
    <div class="row responsive-md">
        <div class="col">
            [... resto do código ...]
        </div>
    </div>
</div>

Now, to use the ng-repeat, just set the object name and the array you want to repeat. For this, set the ng-repeat always at the highest level of the block, so that it is repeated creating the ideal layout. For example:

<div ng-if="mediaMobile">
    <div class="row responsive-md" ng-repeat="objeto in lista">
        <div class="col">
            [... resto do código ...]
        </div>
    </div>
</div>

Where "object" will be the parameter to define which field to display, and "list" would be the $scope which contains the array to be displayed.

We assume you have the following array:

$scope.lista = [
    {id:1, nome1: "Comer", nome2: "Dormir", url1:"umaurlcomer.com", url2:"umaurldormir.com"}, 
    {id:2, nome1: "Comer", nome2: "Dormir", url1:"duasurlcomer.com", url2:"umaurldormir.com"},
    {id:3, nome1: "Comer", nome2: "Dormir", url1:"tresurlcomer.com", url2:"umaurldormir.com"}
];

Then you can access the array data within the blocks using the following definition: {{object.noticia}} {{object.url}}. The name 'object' can be any definition you want. But remember to change also when setting ng-repeat. If you change in one, you must change in the other too.

Edited:

Based on our talk in the comments, let’s imagine the following scenario:

  • Array of news containing 5 news;
  • Each news item has title, text, image and a link;

Let’s assume that the structure of this news array is this:

$scope.listNoticias = [
    {id:1, titulo:"Nova noticia 1", texto: "Corpo do texto...", img:"img/noticia1.jpg", link:"link/noticia/01.php"},
    {id:2, titulo:"Nova noticia 2", texto: "Corpo do texto...", img:"img/noticia2.jpg", link:"link/noticia/02.php"},
    {id:3, titulo:"Nova noticia 3", texto: "Corpo do texto...", img:"img/noticia3.jpg", link:"link/noticia/03.php"},
    {id:4, titulo:"Nova noticia 4", texto: "Corpo do texto...", img:"img/noticia4.jpg", link:"link/noticia/04.php"},
    {id:5, titulo:"Nova noticia 5", texto: "Corpo do texto...", img:"img/noticia5.jpg", link:"link/noticia/05.php"}
];

To show these news inside your block automatically, simply set the ng-repeat at the highest hierarchical level of the block to be repeated. In your case, it would be the <div class="row"> that would look like this: <div class="row" ng-repeat="noticia in listNoticias".

With this, Angularjs himself will already take charge of recreating this whole block 5 times for you. The only thing you need to define now, is where the title will appear, where the text will appear and where the image will appear.

To display the data, you must reference the object referred to in ng-repeat and its name within the array, i.e.: {{noticia.titulo}} {{noticia.text}} {{noticia.img}} and finally {{noticia.link}}.

In the end, your code will be similar to this below:

<div ng-if="mediaMobile">
    <div class="row responsive-md" ng-repeat="noticia in listNoticias">
        <div class="col">
            <a href="{{noticia.link}}">
                <div class="{{noticia.img}}">
                    <div class="texto_categorias_home">
                        <div><i class="fa-fa-cutlery"></i></div>
                        <h1>{{noticia.titulo}}</h1>
                        <p>{{noticia.texto}}</p>
                    </div>
                </div>
            </a>
        </div>
        <!-- aqui você pode definir outros dados a serem exibidos, por exemplo -->
        <div class="col"> 
           <a href="{{noticia.outrolink}}">
               <div class="img_dormir">
                   <div class="texto_categorias_home">
                       <div><i class="fa-fa-bed"></i></div>
                       {{noticia.curiosidade}}
                   </div>
               </div>
           </a>
        </div>
    </div>
</div>

Ready. By doing this, the angular itself will take care of:

  • Identify the array;
  • Know how many reps he should do;
  • Repeat and create Divs automatically;
  • Fill in the data according to the array you had;

Is it clearer now? I hope I have clarified your doubt.

2

I changed your code to work, I warn you that Voce will need to implement another controller called Sharenews

var app = angular.module('myApp', []);
app.controller('ListaNoticiasHome', function($scope, $http) {
    console.log(1);
    $http.get("https://www.sabeonde.pt/api/api_noticias_home.php").success(function (data) {
        $scope.noticias_home = data; 
        console.log(data);
    });
});
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp" ng-controller="ListaNoticiasHome">
    
    <div class="row" ng-repeat="noticias in noticias_home">
        <div class="col">
            <a href="#/app/ver-noticia/{{noticias.url_artigo}}/{{noticias.id}}">
                <div style="background: url(https://www.sabeonde.pt/gtm/anexos/posts_home/{{noticias.id_anexo}}.{{noticias.tipo}}); border-top-left-radius:10px; border-top-right-radius:10px; height: 200px; background-size: 100% 100%; background-repeat: no-repeat;">
                </div>
            </a>
            <div style="border-bottom-left-radius:10px; border-bottom-right-radius:10px; height: 100px; background-color: white;">
                <table border="0" cellpadding="0" cellspacing="0">
                    <tr>
                        <td colspan="2" valign="top">
                            <a href="#/app/ver-noticia/{{noticias.url_artigo}}/{{noticias.id}}"><div style="font-size: 15px; color:black; margin:5px 0px 15px 10px;  font-weight: bold; ">{{noticias.botao}}</div></a>
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">
                          <!-- ... codigo removido, pois não esta especificado o outro controller chamado "PartilhaNoticiasHome"

                           <div id="mostra_gostos" class="mostra_gostos">{{noticias.likeCount}}</div>
                           <div ng-click="partilhar({{noticias.id}})" ng-controller="PartilhaNoticiasHome" class="botao_posts"><i class="fa fa-share-alt"></i> Partilhar</div>
                           <a href="#/app/ver-noticia/{{noticias.url_artigo}}/{{noticias.id}}"><div class="botao_posts"><i class="fa fa-search"></i> Ver +dddddd</div></a>

                          --> 
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>

</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.