Spare me the news I’m clicking?

Asked

Viewed 81 times

0

I have a mobile app with an area where I list several news through the ng-repeat. Now I have a taste system (like) of every news where there’s a button to make the news taste.

What happens now is I have to get the id of the news and I’m already getting it, but when I like a news story he rescues the id of another news and not the one I clicked.

PHP

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Content-type: application/json");

require_once("../funcoes/funcoes.php");


$result_posts_home = $conexao->prepare("SELECT * FROM posts_home WHERE activo = :activo ");
$result_posts_home->bindValue(':activo', 1, PDO::PARAM_INT);
$result_posts_home->execute();
$posts_home = $result_posts_home->fetchAll(PDO::FETCH_OBJ);

foreach ($posts_home as $row_posts_home) {

    $result_posts_home_anexos = $conexao->prepare("SELECT * FROM posts_home_anexos WHERE id_mae = :id_mae AND seccao = :seccao ");
    $result_posts_home_anexos->bindParam(':id_mae', $row_posts_home->id, PDO::PARAM_INT);
    $result_posts_home_anexos->bindValue(':seccao', 'thumbnail', PDO::PARAM_STR);
    $result_posts_home_anexos->execute();
    $row_posts_home_anexos = $result_posts_home_anexos->fetch(PDO::FETCH_OBJ);

    // VALIDA SE USER JA TEM LIKE NO POST

    $total_likes = $conexao->prepare("SELECT * FROM likes WHERE id_post = :id_post AND user_id = :user_id ");
    $total_likes->bindValue(':id_post', $row_posts_home->id, PDO::PARAM_INT);
    $total_likes->bindValue(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
    $total_likes->execute();
    $likes = $total_likes->fetch(PDO::FETCH_ASSOC);


    $noticias[] = array(
        'id'         => $row_posts_home->id,
        'id_anexo'   => $row_posts_home_anexos->id_anexo,
        'tipo'       => $row_posts_home_anexos->tipo,
        'likes'      => $row_posts_home->likes,
        'url_artigo' => $row_posts_home->url_artigo,
    );

}

$obj = new stdClass();
$obj->result = $noticias;

Controller

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

        angular.forEach(data.result, function(value, key){
           $partilharRecursos.set('idNoticia', value.id);
        });   
    });
})

View

 <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()" 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.likes}}</div>
                           <a onclick="window.plugins.socialsharing.share('{{noticias.titulo}}', 'SabeOnde', 'https://www.sabeonde.pt/gtm/anexos/posts_home/{{noticias.id_anexo}}.{{noticias.tipo}}', 'https://www.sabeonde.pt/{{noticias.url_artigo}}')" href=""><div class="botao_posts"><i class="fa fa-share-alt"></i> Partilhar</div></a>
                           <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 Like

.controller('LikeNoticiasHome', function($scope, $http, $stateParams, sessionService, $partilharRecursos) {
    var hasLiked = false;
    $scope.like= function (){

        if (!hasLiked) {
            hasLiked = true;
            $scope.liked = 'Não Gosto';
            $scope.likeCount += 1;

            $http.get("https://www.sabeonde.pt/api/api_like_noticias.php?post_id="+$partilharRecursos.get("idNoticia")+ "&user_id=" + sessionService.get('user_id')).success(function (data) {
                $scope.like_noticias_home = data;
            });

        } else {
            hasLiked = false;
            $scope.liked = 'Gosto';
            $scope.likeCount -= 1;

            $http.get("https://www.sabeonde.pt/api/api_unlike_noticias.php?post_id="+$partilharRecursos.get("idNoticia")+ "&user_id=" + sessionService.get('user_id')).success(function (data) {
                $scope.like_noticias_home = data;
            });
        }     
    }
})
  • Could make available the view of controller Listanoticiashome?

  • I edited the question and put it there

  • You have to pass the news id in the click method and capture in your controller the reference in the database. It’s the same thing when you send the route via get... it’s no different than that.

  • How I catch is what I don’t understand

3 answers

1

Good morning Great, would you be able to post the code of your like() function that is in the controller that you did at the angle, probably the problem is in it, before you post it here, you can try to change it, put it without taking the news id by Scope but passing it as a parameter in the function and treating it independently within the like function().

In case with the like when you do that

$scope.like= function (id){
...//cod
}

This function when being called in the view will have to receive a parameter, and in the ng-click of your view, more precisely in the div where you do the like control, just deichar so,

ng-click="like(noticia.id)"

So you pass the ID of the news clicked.

In case I also noticed that you are treating $Scope.liked as a general variable, it would be interesting not to work with it like this, because if you give a value to it, this value will be used throughout Cope, in case to simplify it, you could use Function like receiving as a parameter also a news variable, for example:

<div>... ng-click="like(noticia)"...


   .controller('LikeNoticiasHome', function($scope, $http, $stateParams, sessionService, $partilharRecursos) {
   // var hasLiked = false;
$scope.like= function (noticiaClicada){

    if (!noticia.hasLiked) {
        noticiaClicada.hasLiked = true;
        $scope.noticiaClicada.liked = 'Não Gosto';
        $scope.likeCount += 1;

        $http.get("https://www.sabeonde.pt/api/api_like_noticias.php?post_id="+$partilharRecursos.get("idNoticia")+ "&user_id=" + sessionService.get('user_id')).success(function (data) {
            $scope.like_noticias_home = data;
        });

    } else {
        noticiaClicada.hasLiked = false;
        $scope.noticiaClicada.liked = 'Gosto';
        $scope.likeCount -= 1;

        $http.get("https://www.sabeonde.pt/api/api_unlike_noticias.php?post_id="+$partilharRecursos.get("idNoticia")+ "&user_id=" + sessionService.get('user_id')).success(function (data) {
            $scope.like_noticias_home = data;
        });
    }     
}
})

Ok, in case you can try to use ng-repeat directly in your table code.

<tr ng-repeat="noticia in noticias">
<td colspan="2" valign="top">
    <a href="#/app/ver-noticia/{{noticia.url_artigo}}/{{noticia.id}}"><div style="font-size: 15px; color:black; margin:5px 0px 15px 10px;  font-weight: bold; ">{{noticia.titulo}}</div></a>
</td>
                </tr>
                <tr>
                    <td valign="top">
                       <div ng-init="liked='Gosto'" ng-click="like(noticia.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">{{noticia.likes}}</div>
                       <a onclick="window.plugins.socialsharing.share('{{noticia.titulo}}', 'SabeOnde', 'https://www.sabeonde.pt/gtm/anexos/posts_home/{{noticia.id_anexo}}.{{noticias.tipo}}', 'https://www.sabeonde.pt/{{noticia.url_artigo}}')" href=""><div class="botao_posts"><i class="fa fa-share-alt"></i> Partilhar</div></a>
                       <a href="#/app/ver-noticia/{{noticias.url_artigo}}/{{noticia.id}}"><div class="botao_posts"><i class="fa fa-search"></i> Ver +</div></a>
                    </td>
                </tr>

In this case I did above, I just took that array that you feed in php foreach and put it to feed variables in the table, now it should no longer get the wrong news id, but in this case the foreach that used in the controller Listnewsit will no longer be necessary ok.

  • I already put the controller like how I can do this ?

  • In case I edited the answer why I had not seen that you had put the like of the controller, sorry big, it was just a little lack of attention even.

  • Still giving taking the wrong id

  • And the rest from above the image and all as they will appear if you change ng-repeat to the table

  • When you do ng-repeat within the table, the angular takes care of repeating the code using the values of the playing array into independent variables, replicating the code within the <table> without harming the execution of the code.

  • But repeat the buttons

  • repeats yes, because they are within the table content.

  • But you can’t repeat

  • In this case you can try to leave the buttons out of the table code, and in ng-click continues the way it is, but the bad thing is that leaving them out you will have to add another ng-click where it calls a function receiving a parameter like the one that exists today that will feed a variable inside the angular and after that it calls the function to record the like

  • The most correct would be to repeat the like button to register news, would make the code more readable and the usability of the system would be better on the part of the user, so it would be better for you to follow each like of the news

  • Great went right implementing the code?

Show 6 more comments

0

How are you calling the like() within a ng-repeat, recommend that you pass the id from ng-repeat for the function like(). It is common to have this type of problem, because in the loop of repetition the angular isolates the scopes.

It would look something like this:

angular.module("myApplication", [])
  .controller("myCtrl", function($scope) {
    $scope.notices = [];
    $scope.notices.push({id: 1, name: "AAA"});
    $scope.notices.push({id: 2, name: "BBB"});
    $scope.notices.push({id: 3, name: "CCC"});

    $scope.like = function(notice_id) {
      alert('Id da notícia: ' + notice_id);
    };
  });
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <div ng-app="myApplication" ng-controller="myCtrl">
    <h2>POSTS</h2>
    <table>
      <tr>
        <th>ID</th>
        <th>NAME</th>
      </tr>
      <tr ng-repeat="notice in notices">
        <td ng-bind="notice.id"></td>
        <td ng-bind="notice.name"></td>
        <td>
          <button type="button" ng-click="like(notice.id)">like</button>
        </td>
      </tr>
    </table>
  </div>
</body>

</html>

  • 1

    You can give the example in my controller that I have how it would look ?

0


From what I see, you just go through the id into your Scope, and process your method for the same:

.controller('LikeNoticiasHome', function($scope, $http, $stateParams, sessionService, $partilharRecursos) {
    var hasLiked = false;
    $scope.like= function (id) {

      if (!hasLiked) {
         hasLiked = true;
         $scope.liked = 'Não Gosto';
         $scope.likeCount += 1;

         $http.get("https://www.sabeonde.pt/api/api_like_noticias.php?post_id=" + id + "&user_id=" + sessionService.get('user_id')).success(function (data) {
            $scope.like_noticias_home = data;
         });

      } else {
        hasLiked = false;
        $scope.liked = 'Gosto';
        $scope.likeCount -= 1;

        $http.get("https://www.sabeonde.pt/api/api_unlike_noticias.php?post_id=" + id + "&user_id=" + sessionService.get('user_id')).success(function (data) {
            $scope.like_noticias_home = data;
        });
      }  

    }
});

And in your view:

<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.likes}}</div>
                           <a onclick="window.plugins.socialsharing.share('{{noticias.titulo}}', 'SabeOnde', 'https://www.sabeonde.pt/gtm/anexos/posts_home/{{noticias.id_anexo}}.{{noticias.tipo}}', 'https://www.sabeonde.pt/{{noticias.url_artigo}}')" href=""><div class="botao_posts"><i class="fa fa-share-alt"></i> Partilhar</div></a>
                           <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>

Browser other questions tagged

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